Sub topic 11
Async iterables, generators, and `for await`
Assume you know TypeScript functions, generics, unions, and JavaScript async/await. You should also know that Promise<T> represents a value that will arrive later. This chapter applies that model to sequences of values that arrive over time.
Async iterables represent streams of values
An async iterable is an object that can produce values one at a time, with each value potentially arriving asynchronously. It implements a method named Symbol.asyncIterator.
The for await...of statement consumes an async iterable:
for await (const item of source) {
console.log(item);
}The loop waits for each item before running the body again. This is useful for paginated API results, file chunks, messages, and event streams.
| Type | Meaning |
|---|---|
| `AsyncIterable<T>` | A source that can be consumed asynchronously and yields `T` |
| `AsyncIterator<T>` | An object that produces promises for iterator results |
| `AsyncGenerator<T, R, N>` | A generator that yields `T`, returns `R`, and accepts `N` sent into it |
The first type parameter is the one you use most often. For example, AsyncIterable<string> produces strings.
Async generators produce typed values
An async generator is a function declared with async function*. It can pause at each yield, and the caller receives each yielded value through a promise.
function wait(ms: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms);
});
}
async function* pages(
total: number,
): AsyncGenerator<number[], void, undefined> {
for (let page = 0; page < total; page++) {
await wait(100);
yield [page * 2, page * 2 + 1];
}
}
async function sumPages(): Promise<number> {
let sum = 0;
for await (const values of pages(3)) {
for (const value of values) {
sum += value;
}
}
return sum;
}
sumPages().then((sum) => console.log(sum)); // 15AsyncGenerator<number[], void, undefined> means:
- Each
yieldproduces anumber[]. - The generator eventually returns
void. - The caller cannot send a meaningful value back with
next.
The loop does not request the next page until its current body finishes. This provides a simple form of backpressure: the producer does not run ahead indefinitely.
Accept async iterables in functions
Accept the least specific type that your function needs. If a function only reads values, use AsyncIterable<T> instead of requiring callers to provide an AsyncGenerator.
async function collect<T>(source: AsyncIterable<T>): Promise<T[]> {
const items: T[] = [];
for await (const item of source) {
items.push(item);
}
return items;
}This function works with any compatible async source, including an async generator:
async function* names(): AsyncGenerator<string, void, undefined> {
yield "Ada";
yield "Grace";
}
async function printNames(): Promise<void> {
const allNames = await collect(names());
for (const name of allNames) {
console.log(name);
}
}The generic type T is inferred as string. The helper preserves the element type without repeating it at the call site.
Errors and cleanup
An error thrown inside an async generator rejects the promise requested by the loop. Handle it around the loop when the caller can recover:
async function readSafely(
source: AsyncIterable<string>,
): Promise<string[]> {
const lines: string[] = [];
try {
for await (const line of source) {
lines.push(line);
}
} catch (error: unknown) {
if (error instanceof Error) {
console.error(`Reading failed: ${error.message}`);
} else {
console.error("Reading failed with an unknown value");
}
}
return lines;
}If the loop ends early with break, the iterator can receive a cleanup request through its return method. Generators can use try and finally to release resources such as file handles or subscriptions.
async function* resourceStream(): AsyncGenerator<string> {
try {
yield "data";
} finally {
console.log("close the resource");
}
}Use for await when values arrive over time. Use an ordinary for...of loop when all values are already available synchronously.
Exercise
What is the element type of value in for await (const value of pages(3)), and why does the loop wait between iterations?
Show answer
value is a number[] because the generator yields number arrays. The loop waits because each generator step returns a promise, and for await awaits that step before continuing.