DEV Community

Cover image for Don't use async await with forEach in javascript
Md. Asif Rahman
Md. Asif Rahman

Posted on

Don't use async await with forEach in javascript

If you are using async await in loop, then please use for...of or for(...;....;...) instead of forEach.

Because, Array.prototype.forEach can not be used in async code or has not been designed for this. I did not know this before I faced weird behaviour of forEach loop in async code.

Let's have a look with an example code:

const fruits=["mango","apple","banana","grape"];

fruits.forEach(async(fruit)=>{
  console.log(await Promise.resolve("I am first promise"));
  console.log(await Promise.resolve("I am second promise"));
});
Enter fullscreen mode Exit fullscreen mode

So, in the above code snippet we are looping through the fruits and and trying to resolving two promises one by one with await keyword to run them one by one.

We are actually expecting the result as follows :

"I am first promise"
"I am second promise"
"I am first promise"
"I am second promise"
"I am first promise"
"I am second promise"
"I am first promise"
"I am second promise"
Enter fullscreen mode Exit fullscreen mode

But, We are actually getting the result as follows:

"I am first promise"
"I am first promise"
"I am first promise"
"I am first promise"
"I am second promise"
"I am second promise"
"I am second promise"
"I am second promise"
Enter fullscreen mode Exit fullscreen mode

This happens because forEach does not wait for each promise to resolve.

Reasons behind such problem:
(a) forEach is not designed keeping async await in mind
(b) forEach accepts a callback function that does not return any promise

N.B. We can use map, reduce, flatMap and reduceRight with async await but not forEach and filter as well

Top comments (3)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
devasadnur profile image
Asad Nur

Useful information. Thanks for sharing.

Collapse
 
maniruzzamanakash profile image
Maniruzzaman Akash

Thanks for sharing.