/

How to Use `await` in a Loop in JavaScript

How to Use await in a Loop in JavaScript

In JavaScript, you can use the for..of loop to iterate over an array and await inside the loop. Here’s how you can do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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()

To await inside the loop, you need to place the loop in an async function and use the await keyword. The loop will stop the iteration until the promise being awaited resolves.

You can also use the for..in loop to iterate over an object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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()

The same structure can be used with while, do..while, or for loops as well.

However, it’s important to note that you cannot use await with Array.forEach() or Array.map().

Tags: JavaScript, async/await, loops