How to await in a loop in JavaScript

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

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:

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().

Download my free JavaScript Handbook!