实现说明
await 标出每个异步边界——没有 fire-and-forget。
使用要点
node:fs是 Node.js 内建模块——随运行时自带,无需安装。- 每一步打印都带着自己的标签:
1. poll: I/O callback got、3. check: setImmediate、4. timers: setTimeout 0。
常见问题
运行之前需要装什么吗?
什么都不用装:node:fs 随 Node.js 本体提供。
核心语句
Promise.resolve().then(() => {
console.log('2. microtask: promise');
});
process.on('exit', () => fs.rmSync('report.txt', { force: true }));
setImmediate(() => {
console.log('3. check: setImmediate');
});
代码示例
import fs from 'node:fs';
// Write a file, then read it back asynchronously so the poll phase
// has a real I/O completion to process.
fs.writeFileSync('report.txt', 'ready');
fs.readFile('report.txt', 'utf8', (err, data) => {
console.log('1. poll: I/O callback got', JSON.stringify(data));
// Registered INSIDE the poll callback: setImmediate queues the check
// phase, which runs right after poll finishes — before the timers
// phase of the next loop iteration.
setImmediate(() => {
console.log('3. check: setImmediate');
});
setTimeout(() => {
console.log('4. timers: setTimeout 0');
});
// Microtasks still cut in before any other phase callback.
Promise.resolve().then(() => {
console.log('2. microtask: promise');
});
});
process.on('exit', () => fs.rmSync('report.txt', { force: true }));
// Observed order (node v24, 13 consecutive runs): poll I/O callback first,
// the microtask drains as soon as that callback returns, then the check
// phase runs setImmediate, and setTimeout 0 waits for the next iteration's
// timers phase. Registering these at top level instead gives a different,
// also-reproducible order — timers before check — because no poll callback
// is pending when the loop starts.