简体   繁体   English

仅在执行异步功能后,如何转到循环中的下一个项目?

[英]How to go to next item in the loop only after an async function is done executing?

How can I execute next item in the loop only after async function is successfully done executing? 仅在异步函数成功执行后,如何才能在循环中执行下一个项目?

Here is the sudo code of my current code: 这是我当前代码的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
    });
}

Right now it process all items in the array if successful, other wise it fails. 现在,如果成功,它将处理数组中的所有项目,否则它将失败。 I want to try one item at time. 我想一次尝试一项。 If it is successful, try next item. 如果成功,请尝试下一项。 If not, try again. 如果没有,请再试一次。

What wrong am I doing here? 我在这里做什么错?

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

I am looking for this: 我正在寻找这个:

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's solution worked. 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--;
        }
    }
})();

Since you are using async / await syntax already, just put an await expression in the loop body instead of using then (which just creates a promise, but not block the loop). 由于您已经在使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM