用于循环异步调用

时间:2018-07-03 13:14:53

标签: node.js for-loop asynchronous server

我正面临一个非常棘手的情况,我必须围绕一个异步函数调用循环可能未知的次数。
情况如下,下面的代码在新的Promise中,当调用下面所有代码的函数时,实例化。
我将发布代码的简化版本,然后尝试正确解释问题出在哪里。

// new Promise ....

(async function loop () {
             let i = array1.length
             let results = []
             // the weird syntax here is because I cut some lines
             for (; i > 0; i--) {
               let k = 0
               results = []
               for (; k < array2.length; k++) {
                 let result
                 await asynchFunction(param)
                   .then(res=> {
                     if (res.field) {
                       console.log('SUCCESS')
                       console.log('tries: ' + (entities.length - i + 1))
                       result = res
                       results.push(res)
                     } else {
                       console.log('FAIL')
                       console.log('tries: ' + (entities.length - i + 1))
                     }
                   })
                   .catch(error => {
                     reject()
                   })
               }
               if (results) {
                 // put all results in a single object: resultsData
                 // populate the array resultsData
                 // the resolve here uses the resultData object
                 resolve()
                 break // stop the outer for loop
               }
             }
             // idea: if we get here and nothing failed or resolved it means that no result was found
             resolve(/*the code here tells the somewhere else that the call succeded but no result was found, not relevant for the question*/)
           })() 


好吧,正如您所看到的,我尝试使用this问题答案提出的解决方案进行循环。
这里的问题是,看起来代码在第一次等待后就跳到了最后一个解决方法,并异步执行了其余的循环,我真的不知道为什么。

如果不清楚,请澄清

0 个答案:

没有答案