When it comes to running asynchronous operations for each element in an array, the instinct is often to turn to the trusty
.forEach() method. It seems like the perfect solution, right? However, there’s a catch – a catch that might leave you scratching your head when things don’t work as expected.
Why async/await Inside forEach May Catch You Off Guard
Imagine this scenario: you have an array of user IDs, and for each user ID, you need to fetch the user and push their username into an array. Eventually, you want to log all the usernames. But, much to your surprise, the array remains empty. What gives?
Animation Courtesy: Maxim Orlov
Deep Dive into the Code
As the code starts to run, you’ll notice something intriguing. The
fetchUserById() requests are initiated concurrently within the
forEach() method. These requests are then dispatched to background tasks, waiting until they’re completed – whether it’s through WebAPIs in a browser or the C++ thread pool in Node.js.
With the requests underway, the program forges ahead and logs the usernames array. However, don’t be surprised to find an empty array staring back at you. Why, you ask?
forEach() are oblivious to promises. The callback functions they execute fire synchronously, without any concern for promises that might be lurking in between iterations.
And then, after a bit of time has passed, the requests wrap up, and the usernames array finally gets populated. This happens after the program has moved on and exited, leaving the usernames lingering in obscurity.
Ensure Code Execution Once All Asynchronous Tasks have Concluded
for...of loop is one of the best way for such kind of scenarios.
Array.map() methods can also be used to achieve the same.
forEach and the elegance of
async/await can make all the difference between code that works flawlessly and code that leaves you scratching your head. So, before you dive into your next array-based adventure, take a moment to consider the asynchronous journey that lies ahead. Your future self will thank you!
✨ Thank you for reading and I hope you find it helpful. I sincerely request for your feedback in the comment’s section.