Hello Readers, Welcome back.
You would have wondered why does forEach function on the array does not wait for any asynchronous function even if we provide the async await in the node js. If you are the person, wondered about this ever, this post is right for you.
Non working example :
Lets consider the below snippet, this will not wait for the asynchronous process to wait. I am making a setTimeout to mock the API call async process.
This will result the count as,
Output : count = 0
OMG !! Why it doesn't work ?
Answer probably might be lying inside the Array prototype from JavaScript. Lets take a look inside the "Array.prototype.forEach" function.
From the snippet its clear that, the for loop in which they call the callback function does not wait for the asynchronous process to run in the callback. So this forEach is not build for asynchronous process itself.
So can't I use forEach any more for running a asynchronous function ?
Answer goes like this, "Yes, there are various methods to iterate the array and achieve the asynchronous call" Lets see them one by one below.
Method 1 :
Building a wrapper around the forEach:
As you can see, we made a immediate calling function that return the Promise and we wait for that using the await. To end the wait, we call the resolve in the if condition (index === array.length -1) means the last iteration of the loop.
The same method can be extended using the Array.prototype.forEachAsync to build a wrapper for the forEach as below,
Post creating this in a file called "Array.prototype.forEachAsync.js", include that in the files where you need to use this function, or you can include this globally into the node js.
Now this becomes same as that of using the forEach but with the async support
Method 2 :
Now lets make use of the Promise.all and map of the array to make the same get achieved.
Method 3 :
In similar way, without using any functions, we can even make use of traditional for loop and for in loop
Its always good that we should dig deep into the architecture of the underlying API to create solutions of our own. Hope this post solved the issue of async in the forEachLoop. Thanks readers, keep following and stay tuned !
Comments
Post a Comment