代码没有任何处理:
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
之后执行一个函数。
如何使用Promise
或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
中使用了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)
});
}
多谢大家的评价。
(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
下时,应该是原因。