node.js - 如何等待来自 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
。
如何使用Promise
or重构此代码,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
?
解决方案
在您上次更新时,虽然您使用了async-await
inside for-loop
,但这并没有阻止您的同步流程。
我假设你的imgDownload
和match
函数正在返回承诺。
然后新代码将是:
(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)
});
}
推荐阅读
- spring-webflux - 如何使用反应器有条件地重复或重试
- macos - 如何解释 macOS 的挂起/CPU 使用率诊断文件?文档?
- javascript - ContentEditable div 为每次返回生成 2 个新行
- spring-boot - glassfish/payara容器上的spring boot应用程序jndi
- python - Greenlet 运行时错误和 docker 中部署的应用程序不断启动所有工作人员
- spring - 覆盖常见的spring异常处理程序
- java - 如何使用 Contentful CMA 通过其 id 从 Contentful 获取 CMAEntry 集合
- javascript - 如何发送多个道具并为每个道具执行功能?
- javascript - 在 Web 表单网站中包含 API 端点?
- ms-word - 有没有一种健全的方法可以从 Asciidoc 或 Markdown 等轻量级标记格式生成 Word 或 OpenOffice 文档?