如何等待for循环的多个异步调用? [英] How to wait for multiple asynchronous calls from for loop?
问题描述
没有任何处理的代码:
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
之后需要执行一个功能.
In the above code, imgDownload
is an async function which will download image, match
will match features of downloaded image with another image. Need to execute a function after this for-loop
.
如何使用Promise
或async-await
重组此代码,以便等待每次对异步函数的调用,并且仅在完成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?
使用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");
}
如何在forEach
之后仅执行someFunction
?
推荐答案
在上一次更新中,尽管您在for-loop
中使用了async-await
,但这并没有阻止您的同步流.
With your last update, although you have used async-await
inside for-loop
, but that did't stoped your synchronous flow.
我假设您的imgDownload
和match
函数正在返回promise.
I'm assuming your imgDownload
and match
functions are returning promise.
然后新的代码将是:
(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)
});
}
这篇关于如何等待for循环的多个异步调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!