← 中文资源

简体中文版本

setImmediate 在 I/O 回调之后运行

在 I/O 回调内部注册 setImmediate 与 setTimeout:poll 回调一返回,微任务先清空,随后 check 阶段跑 setImmediate,下一轮 timers 阶段才轮到 setTimeout 0——「check 紧跟 poll」的经典顺序在实测输出里逐行可见。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

1. poll: I/O callback got "ready"
2. microtask: promise
3. check: setImmediate
4. timers: setTimeout 0

实现说明

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.