0

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--;
        }
    }
})();
user7331530
  • 815
  • 1
  • 12
  • 21

1 Answers1

0

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
    }
})();
Bergi
  • 630,263
  • 148
  • 957
  • 1,375