Sub topic 17
for await...of and Async Iterables
This chapter assumes you know Promises and async/await, and that you have read the earlier chapters on the iterable protocol and generators. A plain for...of loop pulls each value as soon as it asks for one. Some sources can't work that way, such as a network stream, paged API results or file chunks. With those, every value arrives later, wrapped in a Promise. for await...of is the loop built for that case.
The async iteration protocol
An async iterable has a method under Symbol.asyncIterator instead of Symbol.iterator. That method returns an async iterator. Its next() returns a Promise that resolves to the usual { value, done } object. The loop awaits each of those Promises before it runs the body, so values are handled one at a time, in order.
Writing and consuming an async generator
The easiest way to make an async iterable is an async function*. Inside it you can both await and yield.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function* ticks() {
yield await delay(100, 'first');
yield await delay(50, 'second');
}
async function main() {
for await (const t of ticks()) {
console.log(t);
}
}
main();
// first
// secondfor await is only valid inside an async function or at the top level of an ES module. Anywhere else it is a syntax error.
Sync iterables of Promises
for await...of also accepts an ordinary iterable. If the iterable has no Symbol.asyncIterator, the loop falls back to Symbol.iterator and awaits each value.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function main() {
const pending = [delay(300, 'slow'), delay(10, 'fast')];
for await (const result of pending) {
console.log(result);
}
}
main();
// slow
// fastAll of these Promises were already running when the loop started. The loop still awaits them in array order, so 'slow' is logged first even though 'fast' settled earlier.
Early exit and errors
The rules from the loop-control chapter still apply. break, return or a thrown error inside the body calls the async iterator's return(), so the generator's finally blocks run. If the source rejects, the loop throws at that point, and you can catch the error with an ordinary try...catch around the loop.
async function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('closed');
}
}
async function main() {
for await (const n of source()) {
if (n === 2) break;
console.log(n);
}
}
main();
// 1
// closedExercise
You have an array of three URLs and want to fetch them all as fast as possible, then log the results. Is for await (const res of urls.map(u => fetch(u))) a good choice, and what is the alternative?
Show answer
Every fetch starts during map, so the requests do run in parallel. The loop then awaits them strictly in array order, and an early rejection may go unhandled while the loop waits on an earlier request. const results = await Promise.all(urls.map(u => fetch(u))) is clearer and fails fast on the first rejection. Use for await...of when values truly arrive one after another, for example from an async generator or a stream.
Exercise
What happens if you write a for await...of loop inside a regular (non-async) function?
Show answer
It is a SyntaxError. for await is only allowed inside async functions (including async generators) and at the top level of ES modules.