# How to await in a loop in JavaScript

> Learn how to use await inside a loop in JavaScript with for...of and for...in, why you must be in an async function, and why forEach and map will not work.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2022-07-27 | Topics: [JavaScript](https://flaviocopes.com/tags/js/) | Canonical: https://flaviocopes.com/await-loop-javascript/

Here is how to use the `for..of` loop to iterate an array and await inside the loop:

```js
const fun = (prop) => {
  return new Promise(resolve => {
    setTimeout(() =>
      resolve(`done ${prop}`), 1000);
  })
}

const go = async () => {
  const list = [1, 2, 3]
	
  for (const prop of list) {
    console.log(prop)
    console.log(await fun(prop))
  }
  
  console.log('done all')
}

go()
```

You need to place the loop in an async function, then you can use `await` and the loop stops the iteration until the promise we're awaiting resolves.

You can do the same with a for..in loop to iterate on an object:

```js
const fun = (prop) => {
  return new Promise(resolve => {
    setTimeout(() =>
      resolve(`done ${prop}`), 1000);
  })
}

const go = async () => {
  const obj = { a: 1, b: 2, c: 3 };

  for (const prop in obj) {
    console.log(prop)
    console.log(await fun(prop))
  }
  
  console.log('done all')
}

go()
```

You could also use `while` or `do..while` or `for` loops too with this same structure.

But you can't await with `Array.forEach()` or `Array.map()`.
