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