DEV Community

Shrihari Mohan
Shrihari Mohan

Posted on • Updated on

🙅🏽‍♂️ Don't use AWAIT inside FOREACH

It won't work as you intended.

Let us see a quick scenario. Consider the following code and guess the output. I am just waiting each second and returning resValue

const arr = [1 ,2 , 3 , 4]
let resValue = 1

const _1SecPromise = () => new Promise((res, rej) => { 
  setTimeout(() => { res(resValue++) }, 1000); 
})

const justFun  = async () => {
  console.log('🚀 Start')

  arr.forEach(async (each) => {
    const val = await _1SecPromise()
    console.log("🚀 each ", val)

   })

  console.log('🚀 End')

}

justFun()
Enter fullscreen mode Exit fullscreen mode

If you guessed it right , Then you may have already the know the concept called Generators. If not just learn it in 2 mins.

Output

Concept of generators.

  • In simple terms , each is called on seperate function that is synchronous.

  • In other words, forEach expects a synchronous function. ForEach does not wait for promises.

  • A simple explanation of how generators work can be seen in following image

Gnerator Explanation

  • Since next() method accepts only synchronous (atleast in this forEach case) promises don't work as intended when we use await.

A simple solution to use await and loops is to use the Good'ol for loop.

const justFun  = async () => {
  console.log('🚀 Start')
  for ( let i = 0 ; i < arr.length ; i ++) {
    const val = await _1SecPromise()
    console.log("🚀 ~ file: index.js ~ line 23 ~ arr.forEach ~ val", i)

  }
  console.log('🚀 End')
}
Enter fullscreen mode Exit fullscreen mode

Trust me this will work as expected.

Result

If you want to know more about how to solve array of promises.
There are some great methods such as

  • The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises.

  • The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.

  • We can use iterators like Map and Reduce also which will work as intended.


If you want to have more clarifications or some mistaked in this post please leave a comment.

If you learnt something new , don't Forget to 💜 !

🧑🏽‍💻 To know which app I used to create a small illustration demonstrating Regular and Genrator functions. Visit PWA apps I use for productivity

🕸 Are you a budding web developer and in need of some cool css websites to learn from Visit Colors & Design

🪓 Using mongoDB ? check out Article on Indexing

And If you like these type of small articles to boost your knowledge, don't forget to follow on dev.to, It motivates to write more and contribute open source.

Peace 🕊 !


Try Our new product for free!

DocsAI - Create AI support agents with your documents in the most affordable price, starts at 0$. Don't need a bot , but need ai help on your docs just upload and start chating !

Using for a company ? Check out our pricing Just contact me for personalized pricing !

docsAi


Oldest comments (0)