gpt4 book ai didi

node.js - 如何等待for循环的多个异步调用?

转载 作者:太空宇宙 更新时间:2023-11-03 22:59:18 25 4
gpt4 key购买 nike

未经任何处理的代码:

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

在上面的代码中,imgDownloadasync function将下载图像,match 将下载图像的特征与另一图像进行匹配。需要在这个for循环之后执行一个函数。

如何使用 Promiseasync-await 重构此代码,以便等待每次对异步函数的调用,并且仅在完成之后>for循环,流程继续吗?

<小时/>

使用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,但这并没有停止您的同步流程。

我假设您的 imgDownloadmatch 函数正在返回 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)
});
}

关于node.js - 如何等待for循环的多个异步调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52276621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com