Open In App

How to use async/await with forEach loop in JavaScript ?

Asynchronous is popular nowadays because it gives functionality of allowing multiple tasks to be executed at the same time (simultaneously) which helps to increase the productivity and efficiency of code.

Async/await is used to write asynchronous code. In JavaScript, we use the looping technique to traverse the array with the help of forEach loop.



NOTE: Using async/await with forEach loop in JavaScript can be a bit tricky since forEach doesn’t inherently support asynchronous operations

Using async/await in for…of loop

Example: This example shows the implementation of the above-explained approach.




async function processArray(array) {
  for (const item of array) {
    await someAsyncFunction(item);
  }
}
 
async function someAsyncFunction(item) {
  // Simulating an asynchronous operation
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(item);
      resolve();
    }, 1000);
  });
}
 
const myArray = [1, 2, 3, 4, 5];
 
processArray(myArray);

Output: 

Using Promise.all() with map

Example: This example shows the implementation of the above-explained approach.




async function processArray(array) {
  await Promise.all(array.map(async item => {
    await someAsyncFunction(item);
  }));
}
 
async function someAsyncFunction(item) {
  // Simulating an asynchronous operation
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(item);
      resolve();
    }, 1000);
  });
}
 
const myArray = [1, 2, 3, 4, 5];
 
processArray(myArray);

Output:

Explanation: Due to the delay in printing elements, another element ” for ” is printed before the first element “geeks” in myArray to save time. It depicts that the asynchronous function run simultaneously.


Article Tags :