Async Generator Backpressure Pipeline
Stream records through async generators so each stage pulls at the pace of the consumer and memory stays flat regardless of source size.
Code
async function* readLines(source: string[]): AsyncGenerator<string> {
for (const line of source) {
await new Promise((resolve) => setTimeout(resolve, 1)); // 模拟 IO
yield line;
}
}
async function* parseJsonLines(lines: AsyncIterable<string>): AsyncGenerator<Record<string, unknown>> {
for await (const line of lines) {
try {
yield JSON.parse(line) as Record<string, unknown>;
} catch {
// 坏行跳过:管道不因单条脏数据中断
}
}
}
async function* onlyEvents(
rows: AsyncIterable<Record<string, unknown>>,
): AsyncGenerator<{ event: string }> {
for await (const row of rows) {
if (typeof row.event === 'string') {
yield { event: row.event };
}
}
}
const raw = ['{"event":"login"}', 'not-json', '{"event":"buy"}', '{"other":1}'];
// for await 拉动整条管道:消费端不取,上游不产(背压由语言内建)
for await (const row of onlyEvents(parseJsonLines(readLines(raw)))) {
console.log('event:', row.event);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
event: login
event: buyHow it works
The structure is a loop within a loop: for (const line of source) outside, for await (const line of lines) inside. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Top-level bindings raw hold the demo state — nothing sits inside a function scope.
Applying it
Expect labeled output — event: — when the file runs.
Statements that matter
await new Promise((resolve) => setTimeout(resolve, 1)); // 模拟 IO
yield line;
for await (const row of onlyEvents(parseJsonLines(readLines(raw)))) {
console.log('event:', row.event);
}
yield JSON.parse(line) as Record<string, unknown>;
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Its state lives in module-level bindings: `raw`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.