← 中文资源

简体中文版本

异步生成器背压管道

用异步生成器串起读取/解析/过滤三级管道:消费端拉动生产节奏(for await 背压内建),坏行跳过不中断,内存恒定。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

event: login
event: buy

实现说明

这里叠了两层循环:for (const line of source) 负责挑选,for await (const line of lines) 负责处理。异步边界用 await 处理,失败以 rejected promise 的形式在调用点浮出,不会被静默吞掉。 演示用的数据放在这几个模块级绑定中:raw。

使用要点

  • 每一步打印都带着自己的标签:event:。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件的状态由几个模块级绑定持有:raw。

核心语句

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>;

代码示例

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);
}