for await Break Triggers Generator Cleanup
Break out of for await and the async generator still cleans up: the consumer-side break calls return(), which runs the finally block that closes resources.
Code
// 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);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
got: event-1
got: event-2
cleanup: closed after 2 events
consumer left the loop
drained: event-1
drained: event-2
drained: event-3
drained: event-4
drained: event-5
cleanup: closed after 5 eventsWhat the code does
The nesting pairs while (n < 5) with for await (const event of pollEvents()) — the inner runs once per outer step. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Caveats
- The guard
event === 'event-2'short-circuits the flow with an earlybreakwhen its condition holds.
Applying it
Running the file prints labeled results such as cleanup: closed after, got:, consumer left the loop — each operation’s effect is visible in the output.
Statements that matter
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);
}
Interactive Tools for This Topic
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library.
Report a problem with this exampleOpens a pre-filled issue on GitHub.