Skip to content

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


→ Get my JavaScript Beginner's Handbook

I wrote 21 books to help you become a better developer:

  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • Svelte Handbook
  • CSS Handbook
  • Node.js Handbook
  • Vue Handbook
...download them all now!

Related posts that talk about js: