简体   繁体   中英

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:

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.

(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 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
    }
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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