How to use async/await feature in a forEach loop in JavaScript
In JavaScript, we can’t directly use async/await keywords with a forEach loop because the forEach loop doesn’t work with asynchronous functions. It doesn’t wait for asynchronous operations to complete before moving to the next iteration.
Problem with using async/await feature in a forEach loop
In JavaScript, async/await is a powerful feature for handling asynchronous operations in a more synchronous-looking way. However, when it comes to using async/await within a forEach loop, there’s a common pitfall that developers often encounter.
Consider the following code:
const items = [1, 2, 3, 4, 5];function someAsyncFunction(it){sleep(100)return it;}items.forEach(async (item) => {let result;try {result = await someAsyncFunction(item);} catch (error) {result = undefined;}console.log(result);});console.log('Loop finished');
Explanation
In this code, we have an array (items) and we want to perform some asynchronous operation (someAsyncFunction) on each item in the array and log the result. However, the output might surprise us when we run this code.
Note: The
someAsyncFunctionfunction is just a dummy method to show the functionality of waiting call/API call.
The forEach loop doesn’t wait for the async function to complete before moving on to the next iteration. As a result, it logs Loop finished before any of the asynchronous operations are completed, and the undefined values are logged because the promises returned by the async functions haven’t been resolved yet.
Solution
However, we can do a workaround to make it possible. While forEach itself doesn't support the async/await feature, we can still use async/await within a forEach loop by defining and immediately invoking an asynchronous function within the map() function as implemented in the code below.
async function dummyArray(array) {await (array.map(async (item) => {// Perform some asynchronous operation using awaitsetTimeout(()=>{console.log(`${item} processed`);},5000)}));}// Usage example:const myArray = [1, 2, 3, 4];dummyArray(myArray);
Explanation
Lines 2–6: We create an
(anonymous async function An anonymous async function in JavaScript is a function that is both asynchronous and doesn’t have a name. It’s defined inline, often used for quick, one-time asynchronous tasks or for passing as callbacks to other functions. async (item)) within themap()function, which allows us to useawaitinside the loop. ThesetTimeoutfunction waits for5000milliseconds here and acts like an API call that can take some time to respond to mimic the functionality of theasync/awaitfeature.
This approach allows us to use async/await feature with a forEach loop-like structure, providing the expected behavior of processing each item in the array asynchronously and in order.
Free Resources