Asynchronous javascript is not everyone’s cup of tea and add to that the complexity of using asynchronous code inside loops and things might start getting out of hand. So, in this article we’ll look at a very useful npm package called await each for javascript.
If you don’t know, it is not possible in Javascript to use asynchronous code with any loop that works on callbacks. For example, javascript promises will work perfectly fine with for and while loops but will not work as expected when it comes to forEach and map etc.
The forEach loop

If you’ve been living under a rock and for some reason do not know what the forEach loop does, it iterates over an array and takes each element as an argument for a callback and executes a callback for each value in the array!
In the above picture you can see how the names of the students are being displayed.
Problem with async forEach

Look at the code above and it’s output. You surely did not want this output from this piece of code, did you? So, why does this happen ? This happens because in a forEach loop the iteration does not wait for the await statement to be executed before going into the next iteration. The code inside each iteration waits for the await but not for going into the next iteration. That is why we get the output that we get.
Using await-each

Well, first of all to be able to use await-each you need to install the await-each npm package and require it in your file. Once you do that you can use awaitEach in the way shown in the code above to get your desired output.
What awaitEach does is wait for any await statement inside the callback and only then iterates to the next iteration. This is helpful in many situations where parallel execution of promises in Promise.all is not the correct solution.
I hope you understood when and where can await-each be used and how it can be helpful to you. If you have any other doubts on how promises are inside loops in Javascript you can take a look at this article ->
Comments
Post a Comment