Lesson 5 of 7
Async Generators & Iterators
Async generators produce a sequence of values asynchronously - ideal for paginated APIs, streaming data, and event sequences. TypeScript types them as `AsyncGenerator<T>` and the `for await...of` loop unwraps each value to `T`.
Async Generators - Typed Async Sequences
// ── Sync generator - for comparison ─────────────────────────
function* range(from: number, to: number): Generator<number> {
for (let i = from; i <= to; i++) yield i;
}
for (const n of range(1, 5)) { console.log(n); } // 1 2 3 4 5
// ── Async generator - AsyncGenerator<T> ──────────────────────
async function* fetchAllTasks(
pageSize = 20,
): AsyncGenerator<Task> {
let page = 1;
let hasMore = true;
while (hasMore) {
const res = await fetch(`/api/tasks?page=${page}&limit=${pageSize}`);
const data: { tasks: Task[]; total: number } = await res.json();
for (const task of data.tasks) {
yield task; // yields one Task at a time
}
hasMore = page * pageSize < data.total;
page++;
}
}
// ── for await...of - consumes typed async sequences ──────────
async function loadAllTasks(): Promise<Task[]> {
const all: Task[] = [];
for await (const task of fetchAllTasks(20)) {
all.push(task); // task is Task ✅
}
return all;
}
// ── Streaming processor - process without loading all in memory ──
async function processTasksInBatches(
batchSize: number,
processor: (batch: Task[]) => Promise<void>,
): Promise<void> {
let batch: Task[] = [];
for await (const task of fetchAllTasks(50)) {
batch.push(task);
if (batch.length >= batchSize) {
await processor(batch);
batch = [];
}
}
if (batch.length > 0) await processor(batch); // flush remainder
}
// ── AsyncIterable typing - accepting any async sequence ───────
async function collectAll<T>(iterable: AsyncIterable<T>): Promise<T[]> {
const results: T[] = [];
for await (const item of iterable) results.push(item);
return results;
}
const allTasks = await collectAll(fetchAllTasks()); // Task[]Common Mistakes
- Loading all paginated results into memory - if there are 1 million tasks, storing them all defeats the purpose of pagination. Use async generators to process incrementally.
- Not typing AsyncGenerator correctly - `async function* gen(): AsyncGenerator<Task>` not `AsyncGenerator<Task, void, unknown>`. The full signature is `AsyncGenerator<Yield, Return, Next>` but defaults (void, unknown) are fine.
- Forgetting error handling in generators - errors thrown inside an async generator propagate to the `for await` consumer. Wrap the generator body in try/catch and yield error sentinels or re-throw.
Tip
Tip
Practice Async Generators Iterators in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Async Generators & Iterators
Practice Task
Note
Practice Task - (1) Write a working example of Async Generators Iterators from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Async Generators Iterators is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- Async generators produce a sequence of values asynchronously - ideal for paginated APIs, streaming data, and event sequences.
- Loading all paginated results into memory - if there are 1 million tasks, storing them all defeats the purpose of pagination. Use async generators to process incrementally.
- Not typing AsyncGenerator correctly - `async function* gen(): AsyncGenerator<Task>` not `AsyncGenerator<Task, void, unknown>`. The full signature is `AsyncGenerator<Yield, Return, Next>` but defaults (void, unknown) are fine.
- Forgetting error handling in generators - errors thrown inside an async generator propagate to the `for await` consumer. Wrap the generator body in try/catch and yield error sentinels or re-throw.
Finished this lesson?