仅在异步函数成功完成执行后,如何才能在循环中执行下一个项目?
这是我当前代码的sudo代码:
$ diff <(grepscript.sh | sort) <(awkscript.sh | sort)
现在,如果成功,它将处理数组中的所有项目,否则将失败。我想一次尝试一项。如果成功,请尝试下一项。如果没有,请重试。
我在这里做什么错了?
async function myAsyncFunction(param) {
try {
// some code
} catch (error) {
// some code
}
}
const myArray = ["one", "two", "three", "four"];
for(let i = 0; i < myArray.length; i++) {
const resultOfMyAsyncFunction = myAsyncFunction(myArray[i]);
resultOfMyAsyncFunction.then(result => {
// some code
});
}
我正在寻找:
for(let i = 0; i < myArray.length;) {
const resultOfMyAsyncFunction = myAsyncFunction(myArray[i]);
resultOfMyAsyncFunction.then(result => {
// some code
})
.then(i++) //Shouldn't i++ happen only after previous .then() is successful?
;
}
Bergi的解决方案有效。
for(let i = 0; i < myArray.length;) {
const resultOfMyAsyncFunction = myAsyncFunction(myArray[i]);
resultOfMyAsyncFunction.then(result => {
// if result is successful, do something
i++;
//else try again
});
}
答案 0 :(得分:0)
由于您已经在使用async
/ await
语法,因此只需在循环主体中放置一个await
表达式,而不要使用then
(这只会创建一个承诺,但是不会阻塞循环。
(async function() {
const myArray = ["one", "two", "three", "four"];
for(let i = 0; i < myArray.length; i++) {
const result = await myAsyncFunction(myArray[i]);
// ^^^^^
if (/* result is successful */) {
// do something
break;
}
// else it goes into next iteration to try again
}
})();