首页 > 解决方案 > 如何等待来自 for 循环的多个异步调用?

问题描述

没有任何处理的代码:

  for (i=0; i<dbImgCount; i++){
        (function(i) {
             imgDownload(FolderPath[i].FolderPath, function (next){
                var url = FolderPath[i].FolderPath;
                const img2 = cv.imread(imgDownload.Filename);
                match({url,
                    img1,
                    img2,
                    detector: new cv.ORBDetector(),
                    matchFunc: cv.matchBruteForceHamming,
                });

            })
        })(i);
      }

在上面的代码中,imgDownload是一个 异步函数,它将下载图像,match将下载图像的特征与另一个图像匹配。在此之后需要执行一个函数for-loop

如何使用Promiseor重构此代码,async-await以便等待对异步函数的每次调用,并且 只有在完成之后for-loop,流程才会继续?


编辑代码async-await

    FolderPath.forEach(FolderPath => {
        (async function () {
            var filename = await imgDownload(FolderPath.FolderPath);
            var url = FolderPath.FolderPath;
            const img2 = cv.imread(filename);
            imgs = await match({url,
                img1,
                img2,
                detector: new cv.ORBDetector(),
                matchFunc: cv.matchBruteForceHamming,
            });
        })();
    });

    function someFunction(){
       console.log("After forEach");
    }

someFunction 之后如何执行forEach

标签: node.jspromiseasync-awaites6-promiseecmascript-2017

解决方案


在您上次更新时,虽然您使用了async-awaitinside for-loop,但这并没有阻止您的同步流程。

我假设你的imgDownloadmatch函数正在返回承诺。

然后新代码将是:

(async function () {

    // Next loop won't be executing without completing last.
    for (i = 0; i < FolderPath.length; i++) {

        var filename = await imgDownload(FolderPath[i].FolderPath);
        var url = FolderPath[i].FolderPath;

        const img2 = cv.imread(filename);

        imgs = await match({url,
            img1,
            img2,
            detector: new cv.ORBDetector(),
            matchFunc: cv.matchBruteForceHamming,
        });
    }

    // Now will wait for for-loop to end
    function someFunction(){
       console.log("After forEach");
    }
// End of async-await
})();

这是一个小示例:

(async function () { 
    for (i=0; i<5; i++) {
        x = await main();
        console.log(x, i);
    }
    console.log("Finally");
})();

// asynchronous main function
function main() {
    return new Promise( (resolve, reject) => {
        setTimeout(()=> { resolve('Done'); }, 5000)
    });
}

推荐阅读