Async/Await Function with loop in javascript | Async/Await with loop

We need to perform some operation on array elements within async and await function. But using forEach loop is a bad choice. We achieve same with the following approach.

1. using map()

Promise.all([1, 2, 3].map(async () => {
    await promiseFunction();
})).catch(err => {
    console.log(err.message);
});
Promise.all([1, 2, 3].map(async () => {
    await new Promise(resolve => setTimeout(resolve, 10));
})).catch(err => {
    console.log(err.message);
});

Using Promise.all(arr.map(asyncFunction)) executes  asyncFunction on all elements of arr in parallel rather than in series. To execute  asyncFunction on all elements of arr in series,we can use a for/of loop.

2. using for/of

for (let elm of arr) {
  await asyncFunction(elm);
}

Leave a Reply