The Wayback Machine - https://web.archive.org/web/20250118001949/https://www.geeksforgeeks.org/how-to-use-async-await-with-foreach-loop-in-javascript/
Open In App

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

Last Updated : 20 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

  • The processArray function iterates over an array asynchronously using a for...of loop.
  • An asynchronous operation is simulated by the someAsyncFunction, utilizing setTimeout within a Promise.
  • The await the keyword is used inside the loop to pause execution until the asynchronous operation for the current item is complete.
  • The provided code demonstrates the asynchronous processing of an array (myArray) using the processArray function, allowing controlled execution of asynchronous operations for each item.

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

Javascript




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: 

javscrip

Using Promise.all() with map

  • In this appraoch, we are creating a function in which we are creating a promise.
  • We are creating another function and returning a promise. in which we are using setTimeout() function to print the item in th console.
  • After that we are declaring an array and passing it to the above created function.

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

Javascript




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:

javscrip2

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.


Become an expert in solving problems with DSA JavaScript—the course designed to teach you Data Structures and Algorithms using JavaScript. Over the next 90 days, dive deep into key DSA concepts, learn to optimize your code, and gain hands-on experience solving challenging problems. Whether you're a beginner or looking to refine your JavaScript skills, this course will provide the knowledge you need to succeed.
Take on the Three 90 Challenge today! Complete 90% of the course within 90 days, and you’ll earn a 90% refund. This challenge is your chance to stay motivated, improve your skills, and get rewarded for your progress. Don’t wait—start your journey to DSA mastery with JavaScript today!


Next Article

Similar Reads

three90RightbarBannerImg