Sub topic 3
Consuming Async Iterables with for await...of
The previous chapter defined the async iteration protocol. An async iterable has a Symbol.asyncIterator method. That method returns an iterator, and the iterator's next() returns a Promise of a { value, done } result. You can drive that protocol by hand, but the language gives you a loop for it: for await...of. This chapter covers what the loop does internally, where you can write it, how its timing works, and the mistakes people make with it most often.
This chapter assumes you know Promises and async/await, ordinary for...of loops, and the sync and async iteration protocols from the earlier chapters. You also need Node.js 18 or later, or a modern browser console, to run the examples.
The Basic Shape
The loop reads like for...of with an await added after for:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function delayedValues(values, ms) {
return {
[Symbol.asyncIterator]() {
let index = 0;
return {
async next() {
await sleep(ms);
if (index < values.length) {
return { value: values[index++], done: false };
}
return { value: undefined, done: true };
}
};
}
};
}
async function main() {
for await (const word of delayedValues(['alpha', 'beta', 'gamma'], 100)) {
console.log(word);
}
console.log('loop finished');
}
main().catch(console.error);
// alpha, beta, gamma (about 100 ms apart), then: loop finisheddelayedValues is a small async iterable that waits 100 ms before handing out each value. The rest of this chapter reuses it. You can declare the loop variable with const, let, or a destructuring pattern such as for await (const [key, value] of entries). The usual loop controls break, continue, labels, and return all work inside the body.
What the Loop Does Internally
Roughly, the loop expands into this code:
async function manualLoop(source) {
const iterator = source[Symbol.asyncIterator]();
while (true) {
const result = await iterator.next();
if (typeof result !== 'object' || result === null) {
throw new TypeError('Iterator result is not an object');
}
if (result.done) break;
const word = result.value;
console.log(word); // the loop body
}
}The expansion leaves out one thing. When the body exits early through break, return, or a thrown error, the real loop also calls iterator.return() if that method exists. The chapter "Breaking Out Early and Cleaning Up" covers that part.
The expansion leads to a few rules:
- The loop calls
[Symbol.asyncIterator]()once, at the start. If the object has no such method, the loop looks forSymbol.iteratorinstead and wraps the sync iterator. The chapter "for await...of over Sync Iterables and Promise Arrays" covers that fallback. If the object has neither method, the loop throws aTypeErrorbefore it runs any iteration. - The loop awaits every
next()call.next()can return a plain object instead of a Promise, becauseawaitaccepts any value, but the protocol says it should return a Promise. - The awaited result must be an object. If
next()resolves toundefined, you get aTypeErroralong the lines of "Iterator result undefined is not an object". - The loop only checks whether
doneis truthy. A result that leaves outdonecounts as not done.
Where You Can Write It
for await is only valid where await is valid:
| Location | Allowed? | Notes |
|---|---|---|
| `async function`, async arrow function, async method | Yes | The most common place |
| `async function*` (async generator) | Yes | Covered in the next chapter |
| Top level of an ES module | Yes | `.mjs` files, `"type": "module"`, `<script type="module">` |
| Plain `function` or arrow function | No | `SyntaxError` at parse time |
| Top level of a CommonJS script | No | `SyntaxError`; wrap the loop in an async function |
| Inside a `forEach`/`map` callback that is not async | No | The callback is its own function scope |
Top-level use in a module looks like this:
// main.mjs (run with: node main.mjs)
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const numbers = {
[Symbol.asyncIterator]() {
let n = 0;
return {
async next() {
await sleep(50);
n++;
return n <= 3 ? { value: n, done: false } : { value: undefined, done: true };
}
};
}
};
for await (const n of numbers) {
console.log(n); // 1, 2, 3
}
console.log('module finished');The Loop Is Sequential and Pull-Based
The consumer drives the loop. The loop calls next() again only after the body for the previous value has finished, including any await inside the body. In other words, a slow body slows down how fast the loop asks for values:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function delayedValues(values, ms) {
return {
[Symbol.asyncIterator]() {
let index = 0;
return {
async next() {
await sleep(ms);
return index < values.length
? { value: values[index++], done: false }
: { value: undefined, done: true };
}
};
}
};
}
async function main() {
const start = Date.now();
for await (const v of delayedValues(['a', 'b', 'c'], 100)) {
console.log(`${v} received at ${Date.now() - start} ms`);
await sleep(200); // slow consumer
}
console.log(`done at ${Date.now() - start} ms`);
}
main().catch(console.error);
// a received at ~100 ms
// b received at ~400 ms
// c received at ~700 ms
// done at ~1000 msEvery step takes about 300 ms: 100 ms waiting for the producer, then 200 ms in the body. The two never overlap. This gives you natural backpressure, because a source that produces on demand never runs ahead of its consumer. The cost is lost parallelism. If the items are independent tasks that could all run at once, for await...of runs them one after another. The chapter "Sequential Loops versus Concurrent Work" explains when to choose Promise.all instead.
A loop also takes control away from the code that follows it in the same function. Code after the loop waits until the source reports done: true. If the source never finishes, as with a live event feed, code after the loop never runs. Put that kind of loop in its own async function, and call that function without awaiting it if other work has to continue.
Gotcha: The Value Itself Is Not Awaited
The loop awaits the result of next(). It does not await result.value. Async generators await the values they yield, so with generators you never notice. A hand-written iterator that puts a Promise into value passes that Promise straight to your loop:
const promiseValues = {
[Symbol.asyncIterator]() {
let i = 0;
return {
next() {
i++;
if (i > 2) return Promise.resolve({ value: undefined, done: true });
return Promise.resolve({ value: Promise.resolve(i * 10), done: false });
}
};
}
};
async function main() {
for await (const v of promiseValues) {
console.log(v); // Promise { 10 }, then Promise { 20 }
console.log(await v); // 10, then 20
}
}
main().catch(console.error);The rule is different for sync iterables. When for await wraps a sync iterator, it does await each value. That difference is why for await (const x of [p1, p2]) hands you resolved values. If you write an async iterator by hand, resolve the value before you put it in the result object.
Common Mistakes
Using for...of on an async iterable
A plain for...of looks only for Symbol.iterator. An object that implements only Symbol.asyncIterator makes it throw TypeError: ... is not iterable. An async generator object has the same problem. Add await after for to fix it.
Using an async callback with forEach
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function wrong() {
[300, 100].forEach(async (ms) => {
await sleep(ms);
console.log('wrong:', ms);
});
console.log('wrong: after forEach'); // prints first
}
async function right() {
for await (const ms of [300, 100]) {
await sleep(ms);
console.log('right:', ms);
}
console.log('right: after loop'); // prints last
}
wrong().then(() => new Promise((r) => setTimeout(r, 500))).then(right);forEach ignores the Promises its callback returns. It starts both callbacks and returns right away, so wrong prints "after forEach" first, and then 100 finishes before 300. Arrays also have no async iterator, so for await uses the sync fallback here. A plain for...of with await in the body would act the same, and with an array of numbers it is the clearer choice.
Not handling the outer Promise
An async function that contains a loop returns a Promise. If the source rejects and nothing catches that Promise, you get an unhandled rejection. In current Node.js, an unhandled rejection crashes the process. Attach .catch() to the top-level call, as these examples do, or use try/catch inside the function. The next chapters cover error handling in detail.
Reusing a consumed iterator
Generator objects and many stream-based sources are single-use. They return themselves from [Symbol.asyncIterator](), so a second loop over the same object finishes immediately or throws. delayedValues creates a fresh iterator on every call, so you can loop over it more than once, but many real sources work differently. To read the data again, create a new source.
| Symptom | Likely cause |
|---|---|
| `SyntaxError` mentioning `await` or an unexpected reserved word | `for await` outside an async function or module |
| `TypeError: x is not async iterable` | Object has neither `Symbol.asyncIterator` nor `Symbol.iterator` |
| `TypeError: x is not iterable` | Plain `for...of` used on an async-only iterable |
| `TypeError: Iterator result ... is not an object` | `next()` resolved to a non-object |
| Loop variable is a Promise | Hand-written iterator put a Promise in `value` |
| Code after the loop never runs | Source never reports `done: true` |
| Second loop yields nothing | Source is single-use and already consumed |
Exercises
Exercise
Using delayedValues(['x', 'y'], 50) from this chapter, a loop body runs await sleep(150) for each value. About how long does the whole loop take, and why?
Show answer
About 450 ms. Each value takes 50 ms to arrive and 150 ms in the body, which is 200 ms per value, 400 ms for two. The loop then calls next() a third time, which waits 50 ms before it reports done: true. The producer and consumer never overlap, because the loop calls next() only after the body finishes.
Exercise
A file named report.js (CommonJS, with no "type": "module" in package.json) contains console.log('start'); followed by a top-level for await (const r of rows) { ... }. What happens when you run it, and how do you fix it?
Show answer
Node throws a SyntaxError while parsing the file, so even 'start' is never printed. Top-level await, including for await, works only in ES modules. Fix it by wrapping the loop in an async function and calling it with .catch(console.error), or by renaming the file to report.mjs or setting "type": "module".
Exercise
A hand-written async iterator's next() returns Promise.resolve({ value: fetch(url), done: false }). Inside for await (const res of source), the code calls res.json() and gets "res.json is not a function". Explain the failure and give two fixes.
Show answer
for await awaits the result of next() but not result.value, so res is the pending Promise from fetch, not a Response. Fix 1: in the consumer, write const response = await res; before calling json(). Fix 2, which is better: inside next(), await the fetch first, as in async next() { const value = await fetch(url); return { value, done: false }; }. An async generator that runs yield fetch(url) would also work, because generators await the values they yield.