实现说明
这里叠了两层循环: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);
}