for await...of
Loops over asynchronous data sources, waiting for each item.
Available since: ES2018
Syntax
for await (const item of asyncIterable) { … }Examples
Looping over an array of promises:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
for await (const value of [wait(100, 'first'), wait(50, 'second')]) {
console.log(value);
}Output:
first
secondAn async generator — data arrives in chunks:
async function* pages() {
for (let page = 1; page <= 3; page++) {
await new Promise((resolve) => setTimeout(resolve, 20));
yield `page ${page}`;
}
}
for await (const page of pages()) {
console.log(page);
}Output:
page 1
page 2
page 3Notes
The order is kept: even if the second promise finishes first, it is printed second.
See also
Related recipes
In the tutorial
- Iterators and generators — How for...of works in JavaScript: iterable objects, iterators and the next method, generator functions with yield, and your own iterable object.