简体   繁体   English

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

[英]How to wait for multiple asynchronous calls from for loop?

Code without any handling: 代码没有任何处理:

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

In the above code, imgDownload is an async function which will download image, match will match features of downloaded image with another image. 在上面的代码中, imgDownload是一个异步函数 ,它将下载图像, match将匹配下载图像的功能与另一个图像。 Need to execute a function after this for-loop . 需要在此for-loop后执行一个函数。

How to restructure this code, using Promise or async-await , so that each call to asynchronous function is waited for and only after completing the for-loop , flow continues? 如何使用Promiseasync-await重构此代码,以便async-await每次对异步函数的调用,并且只有在完成for-loop ,流程才会继续?


Edited the code with async-await : 使用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");
    }

How to execute someFunction only after forEach ? 如何执行someFunction 后才 forEach

With your last update, although you have used async-await inside for-loop , but that did't stoped your synchronous flow. 在上次更新时,虽然你已经在for-loop使用了async-await ,但是没有停止同步流。

I'm assuming your imgDownload and match functions are returning promise. 我假设您的imgDownloadmatch函数正在返回承诺。

Then new Code will be: 那么新的代码将是:

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

Here's a small sample example: 这是一个小样本示例:

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

Thanks everyone for the comments. 多谢大家的评价。

   (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");
    })();

This is working - "After forEach" displays only after for loop. 这是有效的 - 只有在for循环之后才会显示"After forEach" after "After forEach"


When using forEach as mentioned in the answer above. 当使用上面的答案中提到的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
})();

Output is - SyntaxError: await is only valid in async function . 输出为 - SyntaxError: await is only valid in async function

I think await keyword won't be in scope of async function, when it comes under forEach , that should be the reason. 我认为await关键字不在async函数的范围内,当它出现在forEach时,应该是原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM