Async Iterators and for await...of
Async Iterators and for await...of — the core idea
An async iterable yields values over time. for await...of awaits each next step and works naturally with streams or paginated reads. The producer can pause between items without forcing the caller to collect everything first.
What you’ll learn
- Explain async iterators and for await...of with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: Calling numbers creates an async generator. Each for await iteration requests and awaits its next result, then prints 2 and 4 in order. The second yield includes a resolved Promise.
Keep the boundary clear: Do not confuse `for await` with parallel mapping. It normally consumes elements sequentially, which can provide useful backpressure.
See the idea as a flow
Run the complete TypeScript example
Save the code as async-iterators-await.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
async function* numbers(): AsyncGenerator<number> {
yield 2;
yield await Promise.resolve(4);
}
async function main(): Promise<void> {
for await (const value of numbers()) console.log(value);
}
main().catch(console.error);Verified output
2
4Build: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable async-iterators-await.ts; run: node async-iterators-await.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
Calling numbers creates an async generator. Each for await iteration requests and awaits its next result, then prints 2 and 4 in order. The second yield includes a resolved Promise.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
Do not confuse for await with parallel mapping. It normally consumes elements sequentially, which can provide useful backpressure.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Write an async generator yielding the first three square numbers, then sum them in a for await loop.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
An async iterable yields values over time.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.