for await...of and async generators
A generator gives values one at a time, and an async generator gives them one at a time with a wait between them. for await...of is the loop for both: it awaits each value and stops when the source says it has no more, so a program reads a stream of pages with the body of a plain for loop.
The lesson starts with the loop over an async generator that yields at once, then adds a wait between the values, reads the same sequence by hand with next, and ends with a break that closes the generator and runs its cleanup. The generator in the lesson on generators is the synchronous part of this.
for await...of
An async generator is declared with async function*, and calling it returns an async iterator. The loop awaits each value, which is why even a generator that yields plain numbers is read with for await and not with for.
The file forawait.mjs:
async function* numbers() {
yield 1;
yield 2;
yield 3;
}
for await (const value of numbers()) {
console.log('the value:', value);
}
console.log('the loop is done');
node forawait.mjs
the value: 1
the value: 2
the value: 3
the loop is done
The three values arrived in the order they were yielded, and the line after the loop ran once the generator had nothing more. A plain for...of would have given the same numbers here, because nothing waits, but it would fail on the next program, where every value comes from a timer.
An async generator
Inside an async generator, yield may follow an await: the generator waits, then hands the value out and pauses until the loop asks for the next one. That is how a paginated source is written without building the whole list first.
The file pages.mjs:
const delay = (value, ms) =>
new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
async function* pages() {
for (const page of ['first', 'second', 'third']) {
const value = await delay(page, 10);
yield value;
}
}
for await (const page of pages()) {
console.log('a page arrives:', page);
}
console.log('the sequence is done');
node pages.mjs
a page arrives: first
a page arrives: second
a page arrives: third
the sequence is done
Each page was awaited before it was yielded, so the loop body ran once per page and the next request started only when the body asked for the next value. A generator is lazy for that reason: the source is read at the speed of the loop, and a loop that stops early stops the requests too.
Reading it by hand
The loop is a thin layer over the iterator protocol: next() returns a promise of an object with value and done, and the loop calls it until done is true. The program below writes that loop out, which is worth doing once to see what the loop hides.
The file iterator.mjs:
const delay = (value, ms) =>
new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
async function* count(limit) {
for (let n = 1; n <= limit; n += 1) {
yield await delay(n, 10);
}
}
const iterator = count(3);
console.log('a value at a time:');
for (let step = await iterator.next(); !step.done; step = await iterator.next()) {
console.log(' next value:', step.value);
}
console.log('after the last value, done is:', (await iterator.next()).done);
node iterator.mjs
a value at a time:
next value: 1
next value: 2
next value: 3
after the last value, done is: true
The loop asked for a value, awaited the promise that came back and stopped when the object said done. Calling next once more after the end answers done: true again with no value, so a program that reads an iterator by hand does not need to guard the last call.
Leaving the loop early
A break, a return or a throw ends the loop, and the loop then closes the iterator: the generator is resumed with a return, and its finally block runs. That is where a stream closes itself, and it is the reason a generator may hold a resource.
The file early.mjs:
const delay = (value, ms) =>
new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
async function* values() {
try {
for (const value of ['a', 'b', 'c']) {
yield await delay(value, 10);
}
} finally {
console.log('the generator is closed');
}
}
for await (const value of values()) {
console.log('read:', value);
if (value === 'b') {
break;
}
}
console.log('the loop ended early');
node early.mjs
read: a
read: b
the generator is closed
the loop ended early
The third value was never produced, and the cleanup line still ran before the line after the loop. A generator that reads a file or holds a socket gets the same guarantee, which makes for await the loop to use for a source that has something to close.
Exercises
- Add a fourth number to the first generator and check how many lines the program prints.
- Throw inside the generator of the third program after the second value. Which line does the loop print, and does the generator close?
- Read an array of promises with for await and print each value. What does the loop do with a plain number in the same array?
- Add a return of 'stopped' inside the finally block of the last program. What does the loop see?
- Write an async generator that yields the lines of a template string split by a newline, and read them with for await.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does an async generator return when it is called?
Answer
An async iterator whose next returns a promise
The call does not run the body; it returns an iterator that produces each value on demand.
-
What does for await...of do with each value?
Answer
It awaits it and binds the result
The loop awaits the promise of each step, so a plain value is used as it is.
-
Which declaration makes an async generator?
Answer
async function*
The star marks a generator and async marks the waits inside it.
-
What happens to the finally block of a generator when the loop breaks?
Answer
It runs, because the loop closes the generator
The loop asks the iterator to close, and the generator resumes at its finally block.
-
What does this program print?
async function* g() { yield 1; yield 2; } for await (const value of g()) { console.log(value); }Answer
1 / 2
The loop reads the two values in the order they are yielded.
-
What does this program print?
async function* g() { yield "a"; } const iterator = g(); console.log(typeof iterator.next().then);Answer
function
The step of an async iterator is a promise, so it has a then method.
-
What does this program print?
async function* g() { yield 1; yield 2; } const iterator = g(); await iterator.next(); console.log((await iterator.next()).value, (await iterator.next()).done);Answer
2 true
The second step holds the value 2, and the third is past the end.
-
Can for await...of read an array of promises?
Answer
Yes, it awaits each element
The loop awaits every step, so plain values and promises can be mixed in one source.
-
What ends a for await loop?
Answer
A step whose done is true
The loop asks for the next step until the iterator reports that it has no more.
-
What does this program print?
async function* g() { for (const value of [1, 2]) { yield value * 2; } } for await (const value of g()) { console.log(value); }Answer
2 / 4
The generator doubles each value before yielding it, so the loop prints 2 and 4.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev