When async/awit meet forEach, it might not work as you thought…
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 forEach
will 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 imageLink
is 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.
You can see that “done” is show up first, even I added await
in front of forEach
, since forEach
is 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 iterator
to keep track the array element is done or not yet.