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 | const fun = (prop) => { |
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 | const fun = (prop) => { |
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