Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 21, 2022 06:32 pm GMT

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.

console.log(' Start')const _1SecPromise = new Promise((res, rej) => {   setTimeout(() => { res() }, 1000); })const arr = [1 ,2 , 3 , 4]arr.forEach(async (each) => {  await _1SecPromise  console.log(' each ',each )})console.log(' End')

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 forEach Await

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 ++) {    console.log(' each ', i )    await _1SecPromise  }  console.log(' End')}

Trust me this will work as expected.

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 !


Original Link: https://dev.to/shrihari/dont-use-await-inside-foreach-h86

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To