DSA / 3 min read
Miserably Failing Async/Await in Loops?
Common mistakes and best practices when using async/await within loop constructs.
Miserably Failing Async/Await in Loops?
Common mistakes and best practices when using async/await within loop constructs.

How It Broke My Application
I once had a perfectly fine feature completely break because I used async/await inside a forEach().
Yep. No errors. No warnings. Just… nothing worked.
So if you’ve ever been stuck wondering why your await is being ignored inside loops—or why your API calls are firing out of order—you’re not alone.
And this article is the fix I wish I had, because I was not aware how asnyc/await behaves differently inside loop constructs.
Why async/await Fails in Loops
Let’s say you’ve written something like this:
items.forEach(async (item) => {
await fetchData(item);
});Looks innocent, right?
Biggest Mistake Ever.
The problem?
forEach() doesn't wait for promises to resolve. It doesn’t care that you're using await inside.
So what happens?
All your fetchData calls run at the same time—no waiting, no order, no mercy.

The Right Way: Use for...of Loop
If you want your loop to run one at a time, this is the way to go:
for (const item of items) {
await fetchData(item);
}This will wait for each fetchData() call to finish before moving on to the next item.
Want All Requests to Run in Parallel?
Use Promise.all() :
await Promise.all(items.map(item => fetchData(item)));This runs all the promises at once — perfect if order doesn’t matter and you want max speed.
Still Using map() with await?
Be Careful.
items.map(async item => await fetchData(item)); // returns an array of PromisesThis won’t wait for anything unless you wrap it in await Promise.all().
TL;DR

Final Thought
The moment I replaced forEach with for...ofIt felt powerful. As from not knowing wtf is happening to gaining control and understanding of code gives you the supreme feel.
Writing async code in loops is tricky.
But once you understand the behaviour — you’ll never write a broken async loop again.
And you’ll debug others’ code faster too 😉
Have you ever used async inside a loop?
Ever had async code go wild in a loop?
Tell me what happened 👇 I’ll tell you what saved me next!
If you like reading my articles, you can always support my writings by buying me a cup of coffee here ☕️ .
Let me take the hot sip and enjoy 😉

At Dev Simplified, We Value Your Feedback 📊
👉 Want to write with us? Join us on our whatsapp channel
👉 Have any suggestions? Let us know in the comments!