In this tutorial, you will learn why async/await should not be used inside a forEach loop.
forEach() does not wait for async functions.
Example:
// fetchUser
async function fetchUser(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
return await res.json();
}
const users = [1, 2, 3];
users.forEach(async (id) => {
await fetchUser(id); // ❌ wrong way
});
console.log("Done");
Why forEach Fails with async/await
forEach() does not understand Promises. It does not wait for await inside it.
Note: JavaScript moves on without waiting for async tasks.
Correct way 1: Use for.. of loop
Instead of forEach, you can use for.. of loop, when you use await inside it.
for (const id of users) {
await fetchUser(id);
}
In the for.. of loop, it will wait for each async call and run in sequence.
Correct way 2: Promise.all
Promise.all is used when you want to run all async calls in parallel. It is much faster.
Example:
await Promise.all(
users.map(id => fetchUser(id))
);