When async/awit meet forEach, it might not work as you thought…

Frankie
2 min readApr 27, 2020

--

Photo by Joseph Chan on Unsplash

When I first met the problem was trying to upload multiple image to imgur.com then sent image links to database. My approach was simple: Put all the image files in a array, then pass an async function to forEach the function will handle the upload process and put the image link to another array:

I assume that forEachwill wait for it to be done before going to the next entry of the array. If that assumption correct, the imageLink array will store the image links in correct order. However, I find that the links in the imageLinkis not in correct order…

So, I googled and do some experiences to find out the reason.

The mechanism behind forEach is just a loop that call the function you passed in. Here is a short demo to show that forEach will not wait for previous function to be done before going to the next entry of the array. You can just copy it and run in the browser console.

result

You can see that “done” is show up first, even I added await in front of forEach, since forEachis not a promise, it will not return anything, await is not work for it.

Solution:

If you want to run an async function in sequence, you should use for(...of...) because behind the scenes, it is using iteratorto keep track the array element is done or not yet.

--

--

Frankie
Frankie

Written by Frankie

Hi, I am interested in IT field including front-end, back-end, database, networking.

No responses yet