实现说明
while (n < 5) 与 for await (const event of pollEvents()) 嵌套——内层在外层的每一步各跑一遍。异步流被 await 线性化,失败处理保持局部。
使用要点
- 守卫
event === 'event-2'命中后立刻用提前的break结束这一轮。 - 跑完文件,输出里会留下标记——
cleanup: closed after、got:、consumer left the loop。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。
核心语句
await new Promise((r) => setTimeout(r, 5));
for await (const event of pollEvents()) {
console.log('got:', event);
if (event === 'event-2') break;
}
for await (const event of pollEvents()) {
console.log('drained:', event);
}
代码示例
// async 生成器的 try/finally:消费侧 break 会调用生成器的 return(),
// finally 正是在那时执行——用这条通道关闭连接、刷缓冲。
async function* pollEvents() {
let n = 0;
try {
while (n < 5) {
await new Promise((r) => setTimeout(r, 5));
yield 'event-' + ++n;
}
} finally {
console.log('cleanup: closed after', n, 'events');
}
}
// 只消费 2 条就 break:后面的事件永远不再产出,但清理照常执行
for await (const event of pollEvents()) {
console.log('got:', event);
if (event === 'event-2') break;
}
console.log('consumer left the loop');
// 正常耗尽同样走 finally:先产出完再清理
for await (const event of pollEvents()) {
console.log('drained:', event);
}