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
on all elements of asyncFunction
arr
in parallel rather than in series. To execute
on all elements of asyncFunction
arr
in series,we can use a for/of
loop.
2. using for/of
for (let elm of arr) { await asyncFunction(elm); }