Sub topic 12
Composing Async Generators into Pipelines
This chapter assumes you already know how for await...of consumes async iterables, how async function* produces them, how yield* delegates, and how return() and finally run when a loop exits early. Here you combine those pieces into pipelines. A pipeline is a chain of small stages. Each stage consumes one async iterable and produces another.
The working model: stages that pull
Each pipeline stage is an async generator that takes a source and loops over it with for await...of. It then yields zero, one, or many values for each input. Nothing runs until the final consumer asks for a value. When it asks, the request travels upstream one next() call at a time:
- The consumer calls
next()on the last stage. - That stage calls
next()on the stage before it, and so on up to the source. - The source does just enough work (one page, one line, one record) to produce a value.
This pull model makes pipelines lazy. If downstream needs only three items, upstream fetches only as much as it takes to find three.
A complete, runnable pipeline
The example below fakes a paginated API so you can run it in Node.js without a network. The console.log calls show exactly when each page is fetched.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const pages = {
1: { items: [{ id: 1, active: true }, { id: 2, active: false }, { id: 3, active: true }], next: 2 },
2: { items: [{ id: 4, active: true }, { id: 5, active: true }, { id: 6, active: false }], next: 3 },
3: { items: [{ id: 7, active: true }, { id: 8, active: true }], next: null }
};
async function fetchPage(n) {
console.log(`fetching page ${n}`);
await sleep(50);
return pages[n];
}
async function* fetchItems(start) {
let page = start;
try {
while (page !== null) {
const body = await fetchPage(page);
yield* body.items;
page = body.next;
}
} finally {
console.log('fetchItems closed');
}
}
async function* filter(source, predicate) {
for await (const item of source) {
if (predicate(item)) yield item;
}
}
async function* map(source, fn) {
for await (const item of source) {
yield fn(item);
}
}
async function* take(source, limit) {
if (limit <= 0) return;
let count = 0;
for await (const item of source) {
yield item;
if (++count >= limit) return;
}
}
async function main() {
const active = filter(fetchItems(1), (item) => item.active);
const ids = map(active, (item) => item.id);
for await (const id of take(ids, 3)) {
console.log(id);
}
}
main();The output is:
fetching page 1
1
3
fetching page 2
4
fetchItems closedPage 3 is never requested. After take yields its third value, it returns. That exits its for await...of loop, which calls return() on map. Then map exits its loop and calls return() on filter, and filter does the same to fetchItems. The finally block in fetchItems runs last. Cleanup moves up the chain automatically because each stage uses for await...of.
Making composition readable
Nested calls read from the inside out. A small pipe helper lets you list stages in the order data moves through them:
const pipe = (source, ...stages) => stages.reduce((acc, stage) => stage(acc), source);
const ids = pipe(
fetchItems(1),
(src) => filter(src, (item) => item.active),
(src) => map(src, (item) => item.id),
(src) => take(src, 3)
);Common errors
| Mistake | Effect | Fix |
|---|---|---|
| A stage collects the whole source into an array before yielding | Laziness is lost, and every page gets fetched | Yield each item as it arrives |
| A stage loops with manual `next()` calls instead of `for await...of` | Early exit no longer calls `return()` upstream, so cleanup is skipped | Use `for await...of`, or call `source.return()` yourself in `finally` |
| The source opens a resource outside `try/finally` | The resource leaks when a consumer breaks | Wrap the yielding code in `try/finally` |
| Expecting stages to run in parallel | Each item passes through every stage one at a time | Use concurrent patterns, such as batching with `Promise.all`, when throughput matters |
Exercise
In the example above, change take(ids, 3) to take(ids, 5). What does the program print, and is fetchItems closed still logged?
Show answer
It prints "fetching page 1", 1, 3, "fetching page 2", 4, 5, "fetching page 3", 7, "fetchItems closed". The fifth active id, 7, is on page 3, so that page is fetched. Item 8 is never pulled. After take returns, return() travels up the chain, so the finally block still runs.
Exercise
Write a stage chunk(source, size) that yields arrays of up to size items, including a final partial array. Keep it lazy.
Show answer
async function* chunk(source, size) { let buf = []; for await (const item of source) { buf.push(item); if (buf.length === size) { yield buf; buf = []; } } if (buf.length > 0) yield buf; } It holds at most size items at once and yields each full chunk right away, so it stays lazy.