如何等待来自for循环的多个异步调用?

问题描述 投票:1回答:2

代码没有任何处理:

  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是一个async function,它将下载图像,match将匹配下载图像的功能与另一个图像。需要在此for-loop之后执行一个函数。

如何使用Promiseasync-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.js promise async-await es6-promise ecmascript-2017
2个回答
3
投票

上次更新时,尽管你在async-await中使用了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)
    });
}

0
投票

多谢大家的评价。

   (async function () { 
        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,
            });
        }
        console.log("After forEach");
    })();

这是有效的 - "After forEach"仅在for循环后显示。


当使用上面答案中提到的forEach时。

(async function () {

   // Next loop won't be executing without completing last.
  FolderPath.forEach(FolderPath => {

    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,
    });
});

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

输出是 - SyntaxError: await is only valid in async function

我认为await关键字不会在async函数的范围内,当它在forEach下时,应该是原因。

© www.soinside.com 2019 - 2024. All rights reserved.