Sub topic 12
Composing Async Generators into Pipelines
This chapter assumes you already know how for await...of consumes an async iterable, how async function* produces one, and how break or return inside a loop calls the iterator's return() method. You should also be comfortable with yield* delegation and with try/finally inside generators. The goal here is to combine those pieces into small, reusable stages that you chain together.
The Working Model: Source, Stages, Sink
A pipeline is a chain of async iterables where each one reads from the one before it. It has three kinds of parts:
| Part | What it is | Typical form |
|---|---|---|
| Source | Produces the original values | An async generator that fetches pages, reads a file, or polls a queue |
| Stage | Takes an async iterable and yields new values | `async function* stage(source, ...options)` |
| Sink | Pulls values out and does something with them | A `for await...of` loop, or `Array.fromAsync` |
Every stage has the same shape: it accepts any async iterable (or sync iterable) as source, loops over it with for await...of, and yields values. Because a stage both consumes and produces, you can put its output into another stage.
The pipeline is pull-based. Nothing runs until the sink asks for a value. When the sink calls next() on the last stage, that stage calls next() on the stage before it, and so on back to the source. Each value travels the full chain before the next one is requested.
A Runnable Pagination Pipeline
The example below simulates a paged API, so you can run it in Node.js without a network. Each page returns { items, nextUrl }. The source fetches a page only when downstream code needs more items.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const PAGES = {
'/items?page=1': {
items: [{ id: 1, active: true }, { id: 2, active: false }, { id: 3, active: true }],
nextUrl: '/items?page=2'
},
'/items?page=2': {
items: [{ id: 4, active: true }, { id: 5, active: true }, { id: 6, active: false }],
nextUrl: '/items?page=3'
},
'/items?page=3': {
items: [{ id: 7, active: true }],
nextUrl: null
}
};
async function fakeFetchPage(url) {
console.log(`fetch ${url}`);
await sleep(50);
return PAGES[url];
}
// Source: yields items one at a time, fetching pages on demand
async function* fetchItems(url) {
let next = url;
try {
while (next) {
const body = await fakeFetchPage(next);
yield* body.items;
next = body.nextUrl;
}
} finally {
console.log('source closed');
}
}
// Stage: keeps only items that match the predicate
async function* filter(source, predicate) {
for await (const item of source) {
if (predicate(item)) yield item;
}
}
// Stage: stops after `limit` items
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('/items?page=1'), (i) => i.active);
for await (const item of take(active, 3)) {
console.log('got', item.id);
}
console.log('done');
}
main();Output:
fetch /items?page=1
got 1
got 3
fetch /items?page=2
got 4
source closed
doneThree things in this trace matter:
- Page 2 is fetched only after the sink has used up the active items on page 1. The source never reads ahead.
- Page 3 is never fetched. Once
takehas three items, it returns, and nothing pulls from upstream again. source closedprints beforedone. Whentakereturns from inside itsfor await...of, the loop callsreturn()onfilter. Thenfilter's own loop exits and callsreturn()onfetchItems, which runs itsfinallyblock.
That third point is why the chapter on early exit matters here. Cleanup propagates up the chain automatically, as long as every stage uses for await...of to read its source. A stage that calls source.next() by hand loses this behaviour unless it also calls source.return() itself.
Making Stages Composable
Nested calls like take(filter(fetchItems(url), pred), 3) read inside out. A small pipe helper plus curried stages lets you write the chain in the order data flows:
const pipe = (source, ...stages) =>
stages.reduce((upstream, stage) => stage(upstream), source);
const where = (predicate) => (source) => filter(source, predicate);
const limit = (n) => (source) => take(source, n);
async function* map(source, fn) {
for await (const item of source) {
yield await fn(item);
}
}
const select = (fn) => (source) => map(source, fn);
async function main2() {
const ids = pipe(
fetchItems('/items?page=1'),
where((i) => i.active),
select((i) => i.id),
limit(4)
);
for await (const id of ids) console.log(id); // 1, 3, 4, 5
}pipe calls each stage function once to wire up the chain. Calling an async generator function does not run its body, so building the pipeline does no work. Work starts at the first next() from the sink.
The map stage uses yield await fn(item), so fn can be sync or async. In an async generator, yield already awaits a promise operand, so yield fn(item) would also work. The explicit await makes the intent clear, and it makes a rejection throw at a line you can see inside the stage.
Stages That Change the Shape of the Stream
Not every stage maps one input to one output. A batching stage groups items, which helps when the sink writes to a database in bulk:
async function* batch(source, size) {
let buffer = [];
for await (const item of source) {
buffer.push(item);
if (buffer.length === size) {
yield buffer;
buffer = [];
}
}
if (buffer.length > 0) yield buffer; // flush the final partial batch
}Two edge cases to keep in mind:
- The final flush runs only when the source finishes normally. If the consumer breaks out early, the generator is closed at its current
yield, and any items still in the buffer are dropped. If those items must not be lost, flush them in afinallyblock to some side channel, because a closing generator cannot yield more values to its consumer. - If you reassign
bufferinstead of clearing it withbuffer.length = 0, the array you already yielded stays intact. Clearing it in place would empty the array the consumer is still holding.
Error Propagation Through the Chain
Errors travel in the same direction as values:
- If the source throws or a fetch rejects, the error comes out of
filter'sfor await...of, which makesfilterthrow.takerethrows it, and the sink'stry/catchreceives it. A singletry/catcharound the sink loop covers the whole pipeline. - If a middle stage throws (for example, the predicate throws), that stage's
for await...ofcloses its upstream by callingreturn(). The source'sfinallyblock still runs. Then the error continues downstream to the sink. - If the sink's loop body throws, its
for await...ofcallsreturn()on the last stage, cleanup runs all the way up, and the error leaves the loop.
To retry or skip failures, put the handling in the stage closest to the failure. A source can wrap each page fetch in its own retry loop. A stage can catch a per-item error and yield a marker value instead. Once an error has escaped a generator, that generator is finished and cannot be resumed.
Concurrency: Pipelines Are One-at-a-Time
Each item passes through the whole chain before the next is requested. If map awaits a 100 ms call per item, 50 items take about 5 seconds, even though the calls are independent. That fits rate-limited APIs and ordered processing, but it is slow for independent I/O.
You can add bounded concurrency inside one stage by combining batch with Promise.all:
async function* mapConcurrent(source, fn, concurrency) {
for await (const group of batch(source, concurrency)) {
yield* await Promise.all(group.map(fn));
}
}This runs up to concurrency calls at once and keeps output order. It waits for the slowest call in each group before starting the next group. A sliding-window version that starts a new call as soon as one finishes keeps the workers busier but takes more code. Also note that Promise.all rejects as soon as any call fails, and the other calls in that group keep running in the background with their results ignored.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Reusing one generator in two consumers | Each consumer gets some items and the other gets the rest | Build a new pipeline per consumer, or write an explicit fan-out stage |
| Consuming a stage twice | The second loop gets nothing | Generator objects are single-use; call the generator function again |
| Reading the source with manual `next()` calls | Upstream `finally` never runs on early exit | Use `for await...of`, or call `source.return()` in a `finally` |
| Checking the limit before yielding in `take` | One extra upstream pull, possibly an extra request | Yield first, then return when the count is reached |
| Using `Array.fromAsync` on an unbounded source | The program never finishes or runs out of memory | Put `take` before collecting |
| Expecting stages to run in parallel | The pipeline is as slow as the sum of each stage's per-item latency | Add concurrency inside a stage deliberately |
Pipelines versus Arrays
Array methods are eager. pages.flat().filter(...).slice(0, 10) needs every page in memory before the filter runs. A generator pipeline holds one item per stage at a time (plus any buffer a stage keeps), fetches only what the sink asks for, and starts producing output before the source is finished. Choose arrays when the data is small and already loaded. Choose a pipeline when the data is large, unbounded, arrives over time, or costs money or time to fetch.
Exercise
In the pagination example, suppose you change the sink to take(active, 2). Which "fetch" lines print, and does "source closed" print before or after "done"?
Show answer
Only "fetch /items?page=1" prints. Items 1 and 3 are active and both come from page 1, so take returns after yielding item 3 and never pulls again. "source closed" prints before "done", because the return() calls run through filter to fetchItems, and its finally block executes, before the sink's loop finishes.
Exercise
Write a skip(source, n) stage that drops the first n items and yields the rest. Then explain whether pipe(fetchItems(url), where(i => i.active), skip(2), limit(1)) fetches page 2.
Show answer
async function* skip(source, n) { let seen = 0; for await (const item of source) { if (seen++ >= n) yield item; } }. Yes, it fetches page 2. The active items are 1, 3, 4, and so on. skip drops 1 and 3 (both from page 1), so the first item it yields is 4, which comes from page 2. After limit(1) receives item 4, it returns and page 3 is never fetched.
Exercise
A teammate's stage reads its source with const { value, done } = await source.next() in a while loop. Why might a database connection opened in the source's finally-protected block stay open when the consumer breaks early, and how do you fix it?
Show answer
When the consumer breaks, for await...of calls return() on the teammate's stage only. Because the stage does not read its source with for await...of, nothing calls return() on the source, so the source stays suspended at its yield and its finally block never runs. The fix is to read with for await...of, or to wrap the while loop in try/finally and call await source.return?.() in the finally.