How to use async/await in for…of loop In Javascript

  • 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: 

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

Table of Content

  • Using async/await in for…of loop
  • Using Promise.all() with map

Similar Reads

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....

Using Promise.all() with map

...