Skip to content

How to await in a loop in JavaScript

The Valley of Code

Your Web Development Manual

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

β†’ Get my JavaScript Beginner's Handbook
β†’ Read my JavaScript Tutorials on The Valley of Code
β†’ Read my TypeScript Tutorial on The Valley of Code
  • THE VALLEY OF CODE (+ PRO), your web development manual
  • I wrote 15+ free coding BOOKS, download them here
  • SOLOPRENEUR LAND the missing MBA for wannabe solopreneurs craving a life with more freedom, control, fulfillment and purpose (summer 2024)