Sub topic 17
for await...of and Async Iterables
This chapter assumes you know how for...of uses Symbol.iterator and next(), how generator functions work, and how Promises and async/await behave. Here you will extend the same loop to data that arrives over time, such as pages from an API, lines from a file, or chunks from a network stream.
Why a Separate Loop Is Needed
A regular iterator's next() returns a result such as { value, done } right away. That works when the data already exists. When each value has to be fetched or computed asynchronously, the iterator cannot know done until the work finishes. So it returns a Promise of the result instead.
for await...of is the loop for this case. Before each pass it awaits the result of next(), then runs the body with the resolved value.
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);
}
console.log('done');
}
main();
// first
// second
// doneThe loop is only valid inside an async function or at the top level of an ES module. Anywhere else it is a syntax error, just like a bare await.
The Async Iteration Protocol
The async protocol mirrors the sync one with two changes:
| Piece | Sync iteration | Async iteration |
|---|---|---|
| Method that makes the iterator | `[Symbol.iterator]()` | `[Symbol.asyncIterator]()` |
| `next()` returns | `{ value, done }` | `Promise<{ value, done }>` |
| `return()` on early exit | returns a result object | returns a Promise of a result object |
| Generator syntax | `function*` | `async function*` |
| Consuming loop | `for...of` | `for await...of` |
You can drive an async iterator by hand to see what the loop does:
async function* letters() {
yield 'a';
yield 'b';
}
async function main() {
const it = letters()[Symbol.asyncIterator]();
console.log(await it.next()); // { value: 'a', done: false }
console.log(await it.next()); // { value: 'b', done: false }
console.log(await it.next()); // { value: undefined, done: true }
}
main();Writing Your Own Async Iterable
You make an object async iterable the same way you make it iterable, except you use an async * method under Symbol.asyncIterator. Paginated APIs are a common use: the caller loops over items and never deals with page numbers.
// A fake API so the example runs without a network.
const pages = [['ada', 'alan'], ['grace'], []];
const fetchPage = page =>
new Promise(resolve => setTimeout(() => resolve(pages[page] ?? []), 20));
class UserFeed {
async *[Symbol.asyncIterator]() {
let page = 0;
while (true) {
const users = await fetchPage(page++);
if (users.length === 0) return;
yield* users;
}
}
}
async function main() {
for await (const user of new UserFeed()) {
console.log(user);
}
}
main();
// ada
// alan
// gracePages are fetched lazily. Page 1 is not requested until the loop asks for the item after 'alan'. If the consumer stops early, the remaining pages are never fetched.
Built-in Async Iterables
Many runtime APIs already implement Symbol.asyncIterator, so you can loop over them directly:
- Node.js readable streams, including
fs.createReadStream, which yield chunks. readline.createInterfacein Node.js, which yields lines.ReadableStreamin browsers, Deno and recent Node.js releases. Older browsers do not support async iteration ofReadableStream, so check support before relying on it.
// Save as lines.mjs and run: node lines.mjs lines.mjs
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
const rl = createInterface({ input: createReadStream(process.argv[2]) });
let n = 0;
for await (const line of rl) {
n++;
}
console.log(`${n} lines`);This file uses top-level for await because .mjs files are ES modules.
Sync Iterables Work Too
for await...of also accepts an ordinary iterable. If the source has no Symbol.asyncIterator, the loop falls back to Symbol.iterator and awaits each value. Values that are not Promises come through unchanged.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function main() {
for await (const v of [delay(50, 'x'), 'plain', delay(10, 'y')]) {
console.log(v);
}
}
main();
// x
// plain
// yThe output follows array order, not completion order. 'y' settles first but is printed last.
Sequential, Not Parallel
for await...of handles one value at a time. If each step's work starts inside the loop body, the steps run back to back and their times add up.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function main() {
const ids = [1, 2, 3];
console.time('sequential');
for (const id of ids) {
await delay(100, id);
}
console.timeEnd('sequential'); // about 300ms
console.time('parallel');
await Promise.all(ids.map(id => delay(100, id)));
console.timeEnd('parallel'); // about 100ms
}
main();Running steps in order is right when order matters, when each step depends on the previous one, or when you need to limit load on a server. When the tasks are independent and the list is finite, Promise.all is faster.
break, return and Cleanup
Early exit behaves as it does in for...of. The difference is that the loop awaits the iterator's return() method, so async cleanup finishes before execution continues past the loop.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function* connection() {
try {
let n = 0;
while (true) {
await delay(10);
yield n++;
}
} finally {
await delay(10);
console.log('connection closed');
}
}
async function main() {
for await (const n of connection()) {
if (n === 2) break;
console.log(n);
}
console.log('after loop');
}
main();
// 0
// 1
// connection closed
// after loopThe same cleanup runs if the body uses return or throws an error.
Handling Errors
When a Promise from next() rejects, the loop throws at that point. Wrap the loop in try...catch to handle the error.
async function* flaky() {
yield 1;
throw new Error('network down');
}
async function main() {
try {
for await (const v of flaky()) {
console.log(v);
}
} catch (err) {
console.log('caught:', err.message);
}
}
main();
// 1
// caught: network downWhen the error comes from the source, the generator has already finished, so the loop does not call return(). When the error is thrown in the loop body, the loop calls return() first, which runs the generator's finally block, and then the error propagates.
Common Mistakes
- Using
for awaitoutside an async context. This is aSyntaxError. Move the loop into anasyncfunction or a module. - Using
forEachwith an async callback.arr.forEach(async x => { await work(x); })does not wait for anything.forEachignores the returned Promises. Usefor...ofwithawait, orfor await...of. - Looping over a plain object. Objects have neither
Symbol.asyncIteratornorSymbol.iterator, so you get aTypeError. UseObject.entries(obj)instead. - Expecting results in completion order. The loop yields values in the order the source produces them, not the order in which they settle.
Exercise
You have const urls = ['a', 'b', 'c'] and an async function load(url). Explain the difference between for (const u of urls) { console.log(await load(u)); } and for await (const r of urls.map(load)) { console.log(r); }. Which one risks an unhandled rejection, and why?
Show answer
The first loop starts each load only after the previous one finishes, so the requests run in sequence. The second calls map(load) first, which starts all three requests at once, and then awaits the results in array order. The second loop risks an unhandled rejection. If load('c') rejects while the loop is still awaiting load('a'), nothing is attached to the 'c' Promise yet, so it is reported as unhandled. Use Promise.all or Promise.allSettled when you start all the work up front.
Exercise
Write a class Countdown whose instances work with for await...of. new Countdown(3) should yield 3, 2, 1, waiting 100ms before each value.
Show answer
class Countdown { constructor(n) { this.n = n; } async *[Symbol.asyncIterator]() { for (let i = this.n; i > 0; i--) { await new Promise(r => setTimeout(r, 100)); yield i; } } } Then, inside an async function, write: for await (const i of new Countdown(3)) console.log(i);
Exercise
A for await...of loop over an async generator exits with break. The generator's finally block contains an await. Does the code after the loop run before or after that cleanup finishes?
Show answer
After. On break, the loop calls the iterator's return() method and awaits the Promise it returns. That Promise settles only once the generator's finally block has finished, including any awaits inside it.