How to Use async/await with a forEach loop in JavaScript

You cannot use “async/await” directly within the callback function of a forEach loop because forEach does not wait for promises to resolve. Instead, you can a “for loop”, “for…of loop”, or “map() with Promise.all()” function to achieve the desired asynchronous behavior.

Method 1: Using a for loop with async/await

async function processItem(item) {
  // Simulate a delay of 1 second using setTimeout and a Promise
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('Processed item:', item);
      resolve();
    }, 1000);
  });
}

async function processArray(array) {
  for (let i = 0; i < array.length; i++) {
    await processItem(array[i]);
  }
  console.log('All items processed');
}

processArray([11, 18, 19, 21]); 

Output

Processed item: 11
Processed item: 18
Processed item: 19
Processed item: 21
All items processed

In this code example, I’ve added a simple “processItem()” function that simulates a delay of 1 second using “setTimeout()” and a Promise.

The function logs the processed item to the console and resolves the promise after the delay.

You can see the processed items logged to the console individually, followed by the ‘All items processed’ message.

Method 2: Using a for…of loop with async/await

async function processItem(item) {
  // Simulate a delay of 1 second using setTimeout and a Promise
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('Processed item:', item);
      resolve();
    }, 1000);
  });
}

async function processArray(array) {
  for (const item of array) {
    await processItem(item);
  }
  console.log('All items processed');
}

processArray([11, 18, 19, 21]); 

Output

Processed item: 11
Processed item: 18
Processed item: 19
Processed item: 21
All items processed

Method 3: Using the map() with Promise.all()

async function processItem(item) {
  // Simulate a delay of 1 second using setTimeout and a Promise
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('Processed item:', item);
      resolve();
    }, 1000);
  });
}

async function processArray(array) {
  await Promise.all(array.map(async (item) => {
    await processItem(item);
  }));
  console.log('All items processed');
}

processArray([11, 18, 19, 21]); 

Output

Processed item: 11
Processed item: 18
Processed item: 19
Processed item: 21
All items processed

In all three examples, we have a function called the “processArray()” function that takes an array as input and processes each item in the array using an asynchronous function called “processItem()”.

The first two examples use a “for loop” and a “for…of loop”, respectively, while the third example uses the “map() method along with Promise.all()” to process all items in parallel.

After all, items have been processed, the ‘All items processed’ message is logged to the console.

Leave a Comment