[英]How to go to next item in the loop only after an async function is done executing?
仅在异步函数成功执行后,如何才能在循环中执行下一个项目?
这是我当前代码的sudo代码:
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?
;
}
我正在寻找这个:
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
});
}
Bergi的解决方案有效。
(async function() {
const myArray = ["one", "two", "three", "four"];
for(let i = 0; i < myArray.length; i++) {
const result = await myAsyncFunction(myArray[i]);
// ^^^^^
if (result) {
// do something
}
else {
i--;
}
}
})();
由于您已经在使用async
/ await
语法,因此只需在循环体中放置一个await
表达式即可,而不是使用then
(这会创建一个promise,但不会阻塞循环)。
(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
}
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.