Why async await not work in forEach ?
I recently encountered a scenario where I was using async await inside forEach, but it was not working inside foreach loop.
Here is the demonstration of the problem:
In the above code, callback
function passed to forEach
function didn’t respected the async/await. Even though everything is right at least syntactically.
Now, lets dig deeper and try to find the cause, why asycn await didn’t work inside for Each.
The reason for this lies in the first requirement of async and await. And this requirement might not met in every cases, mostly when we are using inbuilt methods.
i.e. await must be used inside a async function.
Consider below code and let us see the order of console.logs
In the above code for Normal Flow
everything is fine. Thing to pay attention is the Special Flow
. We did something new there.
we used call
method to call our simplePromise
method. And this is the reason my code didn’t paused in Special flow
. Beacuse call
method directly call the method without respecting the async tasks. call
method do not uses the async keyword.
And same happens in case of forEach
. If we see the implementation of forEach then we will get to see this line:
callback.call(T, kValue, k, O);
We simply call the callback function and do not care about any asynchronous thing. And due to this forEach
do not respect async await keyword.
So what is the solution for above problem?
Simply use for loops. We can either use ancient for loop or the new for of/in loops. Any variation of these will work.