Sub topic 11
Async iterables, generators, and for await
Some async work produces many values over time instead of one result. Examples include pages from an API, lines from a file, and chunks from a stream. A Promise<T> resolves once, so it cannot model these. TypeScript models them with async iterables, async generators, and the for await loop.
This chapter assumes you know Promise<T>, async/await, generics at the level of Array<T>, and union narrowing. It also assumes you know what a synchronous generator (function*) is.
The protocol behind for await
An async iterable is any object with a [Symbol.asyncIterator]() method that returns an async iterator. The iterator has a next() method that returns a promise of an IteratorResult. TypeScript's types mirror this:
| Type | What it describes |
|---|---|
| `AsyncIterable<T>` | An object you can loop over with `for await`. It has `[Symbol.asyncIterator]()`. |
| `AsyncIterator<T, TReturn, TNext>` | The object with `next()`, and optionally `return()` and `throw()`. |
| `AsyncIterableIterator<T>` | An iterator that is also iterable. Its `[Symbol.asyncIterator]()` returns itself. |
| `AsyncGenerator<T, TReturn, TNext>` | What calling an `async function*` returns. It is an `AsyncIterableIterator` with `return()` and `throw()` guaranteed. |
IteratorResult<T, TReturn> is a union discriminated by done:
{ done?: false; value: T }is a yielded value.{ done: true; value: TReturn }is the final result. For most iterablesTReturnisvoidorany.
Checking done narrows value to the right type, just like any discriminated union.
The AsyncGenerator type has three parameters:
Tis the type of each yielded value.TReturnis the type of the finalreturnvalue. Usevoidwhen nothing is returned.TNextis the type of values passed in throughnext(value). Useundefinedwhen callers pass nothing.
Async generators
An async function* can use both await and yield. Calling it does not run the body. It returns an AsyncGenerator that runs the body step by step as the consumer asks for values.
async function* pages(total: number): AsyncGenerator<number[], void, undefined> {
for (let i = 0; i < total; i++) {
yield [i * 2, i * 2 + 1];
}
}
async function sumAll(): Promise<number> {
let sum = 0;
for await (const page of pages(3)) {
for (const n of page) {
sum += n;
}
}
return sum;
}
sumAll().then((total) => console.log(total)); // 15Here page is number[], taken from the generator's first type argument. You can omit the return annotation and let TypeScript infer AsyncGenerator<number[], void, unknown>. Write it out when the function is part of a public API, so the contract is visible.
A yield in an async generator also awaits its operand. If you write yield somePromise, consumers receive the resolved value, not a promise. The type of T is therefore the unwrapped type, the same idea as Awaited<T> from earlier chapters.
Consuming with for await
for await (const x of source) does four things on each pass:
- It calls
source[Symbol.asyncIterator]()once, before the first pass. - It calls
next()and awaits the promise. - It stops when
doneistrue. - Otherwise it binds
valuetoxand runs the loop body.
The generator is pulled, not pushed. It does no work for the next value until the loop asks for it. A slow loop body therefore slows the producer, which gives you natural backpressure.
for await also accepts ordinary synchronous iterables. It awaits each element, so for await (const x of [p1, p2]) yields resolved values. This runs the promises one after another in the loop, not in parallel. If the promises already exist, Promise.all is usually what you want.
A for await loop is only legal inside an async function, an async generator, or the top level of an ES module. TypeScript reports an error elsewhere.
A reusable pagination generator
The most common use is hiding a paged API behind a flat stream of items. This generic helper takes a loader function and keeps the item type.
interface Page<T> {
items: T[];
next: string | null;
}
async function* paginate<T>(
first: string,
load: (cursor: string) => Promise<Page<T>>,
): AsyncGenerator<T, void, undefined> {
let cursor: string | null = first;
while (cursor !== null) {
const page: Page<T> = await load(cursor);
yield* page.items;
cursor = page.next;
}
}
const fake: Record<string, Page<number>> = {
a: { items: [1, 2], next: "b" },
b: { items: [3], next: null },
};
async function main(): Promise<void> {
const load = async (cursor: string): Promise<Page<number>> => fake[cursor];
for await (const n of paginate("a", load)) {
console.log(n);
}
}
main();Three details matter here:
Tis inferred fromload. The loop variablenisnumberwith no annotation.pagehas an explicit type. Without it,cursordepends onpageandpagedepends oncursor, and the compiler may report an implicitanycaused by a circular inference.yield*delegates to another iterable. Inside an async generator it accepts both sync and async iterables.
Writing an iterable by hand
You rarely need to, but the types are easier to understand once you have seen the raw form. This object counts down from a starting number.
function countdown(from: number): AsyncIterable<number> {
return {
[Symbol.asyncIterator](): AsyncIterator<number> {
let n = from;
return {
async next(): Promise<IteratorResult<number>> {
if (n < 0) {
return { done: true, value: undefined };
}
return { done: false, value: n-- };
},
};
},
};
}
async function show(): Promise<void> {
for await (const n of countdown(2)) {
console.log(n); // 2, 1, 0
}
}
show();An async generator does the same job with less code, and it manages the done bookkeeping for you. Prefer generators unless you need custom return() or throw() behavior.
Early exit and cleanup
A loop can end before the source is exhausted. When it does, the language calls the iterator's return() method, which lets the generator clean up. The loop can end early in these ways:
- a
breakstatement - a
returnstatement - a thrown error in the loop body
A generator runs its finally blocks when this happens.
async function* lines(): AsyncGenerator<string, void, undefined> {
console.log("open");
try {
yield "first";
yield "second";
yield "third";
} finally {
console.log("close");
}
}
async function firstLine(): Promise<string | undefined> {
for await (const line of lines()) {
return line; // triggers return(), so "close" is printed
}
return undefined;
}
firstLine().then((line) => console.log(line));The output is open, close, then first. Put resources such as file handles, connections, and timers inside try/finally in the generator. Without finally, a consumer that breaks early leaks them.
A generator that is never started never runs its finally. If you create a generator and never call next(), no cleanup occurs, but no resource was opened either.
Cancellation with AbortSignal
A break stops the consumer. To stop a producer that is waiting on slow work, pass an AbortSignal into the generator and check it between steps.
function sleep(ms: number): Promise<void> {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
async function* ticks(
intervalMs: number,
signal: AbortSignal,
): AsyncGenerator<number, void, undefined> {
let count = 0;
while (!signal.aborted) {
await sleep(intervalMs);
if (signal.aborted) {
return;
}
yield count++;
}
}
async function demo(): Promise<void> {
const controller = new AbortController();
setTimeout(() => controller.abort(), 250);
for await (const n of ticks(100, controller.signal)) {
console.log(n); // 0, 1
}
}
demo();The generator checks signal.aborted after the await, because the signal may have fired while it slept. If the work inside the generator is a fetch, pass the signal to fetch as well, so the request is cancelled and not merely ignored.
Typing TNext: values flowing in
The third type parameter describes values sent in with next(value). Inside the generator, the result of yield has that type.
async function* accumulator(): AsyncGenerator<number, string, number> {
let total = 0;
while (total < 10) {
const added: number = yield total;
total += added;
}
return `finished at ${total}`;
}
async function runAccumulator(): Promise<void> {
const gen = accumulator();
await gen.next(0); // first call: the argument is ignored
await gen.next(4);
const last = await gen.next(7);
if (last.done) {
console.log(last.value); // string: "finished at 11"
}
}
runAccumulator();The value passed to the first next() call is always discarded, because no yield is waiting for it. This pattern is rare in application code. for await always calls next() with no argument, so a generator with a non-undefined TNext cannot be consumed by for await alone.
Common errors and gotchas
- Sequential bodies.
for awaitfinishes the loop body before asking for the next value. If each iteration does independent slow work, collect the work and usePromise.all, or limit concurrency with a helper. - Single use. A generator can be iterated once. A second
for awaitover the same generator object finds it finished and yields nothing. Call the generator function again to get a fresh one. - Errors surface in the loop. A rejected promise inside the generator makes
next()reject. The error is thrown at thefor awaitline, so wrap the loop intry/catchand narrow theunknowncatch variable as in the error-handling chapter. - Forgetting the async variant.
for (const x of asyncGen())is a compile error, because anAsyncGeneratorhas noSymbol.iterator. Usefor await. - Streams yield
any. Node'sReadablestreams supportfor await, but their chunks are typedany. Treat each chunk as untrusted. Check it, or decode it, before using it as a specific type. - No built-in toolkit. Before
Array.fromAsyncwas widely available, collecting an async iterable meant writing a helper. This generic one keeps the element type:
async function toArray<T>(source: AsyncIterable<T>): Promise<T[]> {
const out: T[] = [];
for await (const item of source) {
out.push(item);
}
return out;
}Because the parameter is AsyncIterable<T>, it accepts generators, hand-built iterables, and streams alike. Accepting the narrowest interface a function needs is a good rule for any helper that consumes iterables.
Exercise
What is the type of chunk in for await (const chunk of gen()) if gen is declared as async function* gen(): AsyncGenerator<Uint8Array, void, undefined>, and what happens to the generator's finally block if the loop body executes break on the first pass?
Show answer
chunk is Uint8Array, the first type argument of AsyncGenerator. A break makes the loop call the generator's return() method, so its finally block runs before the loop statement finishes, and the remaining values are never produced.
Exercise
Write the signature of an async generator take<T> that accepts an AsyncIterable<T> and a count, and yields at most that many items. Why is AsyncGenerator<T, void, undefined> a suitable return type, and what should happen to the source when the count is reached?
Show answer
async function* take<T>(source: AsyncIterable<T>, count: number): AsyncGenerator<T, void, undefined>. It yields items of the source's type T, returns nothing at the end, and receives no values through next(). When the count is reached, the generator should return from inside its own for await over source. Returning from that loop makes the loop call the source's return(), so the source's finally blocks run and its resources are released.