Sub topic 3
Consuming Async Iterables with for await...of
This chapter assumes you know how Promises and async/await work, that you can write a basic for...of loop, and that you have read the previous chapter on the async iteration protocol. The protocol defines what an async iterable is. The for await...of loop is the usual way to read one.
The Loop in One Line
The syntax follows for...of closely, with await added after for:
async function* letters() {
yield 'a';
yield 'b';
yield 'c';
}
async function main() {
for await (const letter of letters()) {
console.log(letter); // a, b, c
}
console.log('done');
}
main();Here letters() is an async generator. The next chapter covers how async generators work. For now, all you need to know is that calling one returns an async iterable. The loop body runs once for each value. The loop binds the resolved value to letter, not a Promise, so the body never has to call .then() or await the item itself.
What the Loop Does on Each Step
The loop is a short sequence of protocol calls with an await at every step. This hand-written version does roughly what for await...of does:
async function* letters() {
yield 'a';
yield 'b';
}
async function manualLoop() {
const iterator = letters()[Symbol.asyncIterator]();
while (true) {
const result = await iterator.next();
if (result.done) break;
const letter = result.value;
console.log(letter); // a, b
}
}
manualLoop();The steps are:
- Call
source[Symbol.asyncIterator]()once to get the iterator. - Call
iterator.next()and await the Promise it returns. - If
doneistrue, leave the loop. - Otherwise bind
valueto the loop variable, run the body, and go back to step 2.
The loop does not call next() again until the body has finished, and that includes any await inside the body. Items are therefore handled one at a time, in order. A later chapter compares this with running work concurrently.
Where You Can Write It
for await...of is allowed in three places:
| Context | Allowed? |
|---|---|
| Inside an `async function`, async arrow, or async method | Yes |
| Top level of an ES module (`.mjs`, or `"type": "module"` in Node.js) | Yes |
| Inside an async generator (`async function*`) | Yes |
| A regular function, or a CommonJS script at top level | No, `SyntaxError` |
In an ES module you can skip the wrapper function:
// main.mjs
async function* nums() {
yield 1;
yield 2;
}
for await (const n of nums()) {
console.log(n); // 1, 2
}Common Errors
The mistakes intermediate developers make most often are:
- Dropping the
awaitkeyword.for (const x of asyncSource)throws theTypeErrordescribed in the callout above. - Using the loop in a non-async callback. Code such as
items.forEach(() => { for await ... })is aSyntaxError, because the callback is not async. - Expecting the loop to return a value. The loop is a statement. To collect results, push them into an array inside the body, or use
Array.fromAsync, which a later chapter covers. - Forgetting that the enclosing function returns a Promise. Code after
main()runs before the loop finishes. Writeawait main()ormain().then(...)when you need the loop's results afterward. - Expecting parallel work. A slow body slows the whole loop, because the next item is not requested until the body finishes.
You can use let instead of const if you need to reassign the loop variable. Each iteration gets a fresh binding either way. for await...of also accepts ordinary sync iterables, such as arrays. That case has its own chapter.
Exercise
What does this program print, and in what order? async function* src() { yield 1; yield 2; } async function main() { for await (const n of src()) console.log(n); } main(); console.log('after');
Show answer
It prints "after", then 1, then 2. Calling main() starts the loop, but the first await inside the loop hands control back to the caller, so console.log('after') runs first. The loop then logs 1 and 2 as each next() Promise resolves.
Exercise
A coworker writes function readAll(source) { for await (const x of source) console.log(x); } and gets a SyntaxError. Give two different ways to fix it.
Show answer
Mark the function async (async function readAll(source) { ... }), or move the loop to the top level of an ES module. In both places for await...of is allowed.