🙅🏽‍♂️ Don't use AWAIT inside FOREACH
Tags: javascript, programming, webdev, beginners
Published: 2022-05-21 18:32:22

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_

```javascript
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()
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fsq3ewqpdddt8vvlm62s.png)
 

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ntzn5hivd3mqlwymyufe.png)

- 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. 
```javascript
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')
}
```

Trust me this will work as expected.

![Result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3md5w4t6t2aas6mctdk9.gif)

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

- The [Promise.all()](https://developer.mozilla.org/en-- US/docs/Web/JavaScript/Reference/Global_Objects/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and [Reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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](https://dev.to/shrihari/top-pwa-apps-i-use-everyday-laptop--4pbn)

🕸 Are you a budding web developer and in need of some cool css websites to learn from Visit [Colors & Design](https://dev.to/shrihari/colors-design-inspiration-websites-for-new-comers-1lcb)

🪓 Using mongoDB ? check out[ Article on Indexing](https://dev.to/shrihari/dont-forget-to-do-this-if-youre-using-mongodb-j36)

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](https://docsai.app/) - 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](https://docsai.app/pricing) Just contact me for personalized pricing !

![docsAi](https://firebasestorage.googleapis.com/v0/b/shrihari-personal-storage.appspot.com/o/banner-docs-jpeg.jpeg?alt=media&token=45c47666-de2a-4e02-8881-beb6e43ce581)

---