实现说明
循环只出现在 for (const entry of pendingWrites),它的每次迭代处理一个元素。await 标出每个异步边界——没有 fire-and-forget。
各个操作都建立在顶层绑定之上:pendingWrites。
使用要点
- 直接运行文件,输出会带上标签,比如
no async work possible inside exit hooks、app work finished, waiting for the loop to drain——输出的每一行都能指回产生它的那次调用。
常见问题
有需要管理的依赖吗?
没有。无需声明或安装任何依赖。 文件用顶层绑定保存自己的状态:pendingWrites。
核心语句
process.on('exit', (code) => {
console.log(`exit hook: flushing ${pendingWrites.length} entries`);
for (const entry of pendingWrites) {
console.log(`flushed: ${entry}`);
}
console.log(`exit hook done, code ${code}`);
});
process.on('exit', () => {
// Timers queued here would never fire: the loop stops after
// the exit handlers return
console.log('no async work possible inside exit hooks');
});
代码示例
// Buffered audit entries that a real app would persist somewhere
const pendingWrites = ['login:u1', 'order:42', 'logout:u1'];
// The exit hook runs once, synchronously, right before shutdown.
// Anything async started inside it will never finish, so only
// synchronous flushes belong here.
process.on('exit', (code) => {
console.log(`exit hook: flushing ${pendingWrites.length} entries`);
for (const entry of pendingWrites) {
console.log(`flushed: ${entry}`);
}
console.log(`exit hook done, code ${code}`);
});
process.on('exit', () => {
// Timers queued here would never fire: the loop stops after
// the exit handlers return
console.log('no async work possible inside exit hooks');
});
console.log('app work finished, waiting for the loop to drain');