Skip to content

For Await Of Loop

for await...of loops over values that arrive asynchronously. On each pass it waits for the next value to be ready, then runs the body with it. Its natural partner is an async iterable, such as an async generator, a stream of chunks or a paged API, where each value is produced only when the loop asks for it. Like await, it can be used only inside an async function or at the top level of a module.

An async generator is declared with async function*. It can await inside its body, and each yield hands one value to the loop. The loop asks for the next value only after the body has finished with the current one:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* readPages(lastPage) {
for (let page = 1; page <= lastPage; page++) {
await wait(50);
yield `page ${page} of ${lastPage}`;
}
}
for await (const page of readPages(3)) {
console.log(page);
}
console.log('all pages read');

This prints:

page 1 of 3
page 2 of 3
page 3 of 3
all pages read

Here wait() stands in for a network request. The line after the loop runs only once every page has been read. Iterator and generator fundamentals covers generators in general.

break, return or an error inside the loop tells the async iterable to finish, which runs any finally block in the generator. That is where a generator closes a file or a connection:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* readPages() {
try {
for (let page = 1; ; page++) {
await wait(20);
yield page;
}
} finally {
console.log('reader closed');
}
}
for await (const page of readPages()) {
console.log('page', page);
if (page === 2) break;
}

This prints:

page 1
page 2
reader closed

The generator has no end of its own, so the break is what stops it, and the loop never requests a third page.

An object is async iterable when it has a Symbol.asyncIterator method. That method returns an object whose next() method returns a promise for { value, done }. An async method returns a promise automatically:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const ticker = {
limit: 3,
[Symbol.asyncIterator]() {
let count = 0;
const limit = this.limit;
return {
async next() {
await wait(50);
count++;
return count <= limit
? { value: `tick ${count}`, done: false }
: { value: undefined, done: true };
},
};
},
};
for await (const tick of ticker) {
console.log(tick);
}

This prints:

tick 1
tick 2
tick 3

The loop calls next() once per pass and stops when the result has done: true. An async generator builds this object for you, so a hand-written iterator is needed only when the protocol has to be controlled directly. Async iterators for big data sets shows a larger example.

for await...of also accepts an ordinary array of promises. It awaits each one in array order, not in the order they settle. The three timers below all start when the array is built, so the slowest one, which comes first, holds up the others:

const wait = (ms, value) =>
new Promise((resolve) => setTimeout(resolve, ms, value));
const start = Date.now();
const deliveries = [wait(300, 'parcel A'), wait(100, 'parcel B'), wait(200, 'parcel C')];
for await (const parcel of deliveries) {
console.log(parcel, `after about ${Math.round((Date.now() - start) / 100) * 100} ms`);
}

This prints:

parcel A after about 300 ms
parcel B after about 300 ms
parcel C after about 300 ms

This use has a trap. If a later promise in the array rejects while the loop is still waiting on an earlier one, nothing is handling that rejection yet, so it is reported as an unhandled rejection. In Node, the program ends with that error even when the loop sits inside try...catch:

const failLater = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
const wait = (ms, value) =>
new Promise((resolve) => setTimeout(resolve, ms, value));
try {
for await (const value of [wait(100, 'ok'), failLater(50, 'lost connection')]) {
console.log(value);
}
} catch (error) {
console.log('caught:', error.message);
}

Running this in Node stops the program with Error: lost connection, and neither ok nor the caught: line is printed. A browser reports the same rejection as uncaught in the console. For promises that have already started, use Promise.all(), which handles every rejection and returns the results in array order:

const wait = (ms, value) =>
new Promise((resolve) => setTimeout(resolve, ms, value));
const results = await Promise.all([wait(300, 'A'), wait(100, 'B'), wait(200, 'C')]);
console.log(results);

This prints:

[ 'A', 'B', 'C' ]

Keep for await...of for sources that produce their values one at a time when asked. Async and await and Combining promises with async and await cover the alternatives.

Steve Griffith covers this topic in his video ESNext for await of loop.