← 中文资源

简体中文版本

nextTick 先于 Promise 微任务执行

同一检查点上 nextTick 队列先于 Promise 微任务清空,两者都赶在 setTimeout 之前:用 nextTick 发就绪信号,监听器再晚注册也能收到。

阅读英文原文

运行结果

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

nextTick -> ready signal -> promise -> timer

实现说明

整个示例围绕函数 onReady组织。 异步边界用 await 处理,失败以 rejected promise 的形式在调用点浮出,不会被静默吞掉。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件在加载时定义 onReady。

签名一览:function onReady(listener)

核心语句

Promise.resolve().then(() => order.push('promise'));
process.nextTick(() => readyListeners.forEach((listener) => listener()));
process.nextTick(() => order.push('nextTick'));

代码示例

const order = [];
const readyListeners = [];
function onReady(listener) {
  readyListeners.push(listener);
}

// Run the probe inside a callback tick — a timer callback is where
// production code actually runs. Module top-level evaluation has its
// own checkpoint semantics and is not where this ordering is relied on.
setTimeout(() => {
  // nextTick callbacks drain before promise microtasks at the same
  // checkpoint, and both finish before any timer fires
  process.nextTick(() => order.push('nextTick'));
  Promise.resolve().then(() => order.push('promise'));

  // nextTick also beats work queued after it — handy for emitting a
  // ready signal right after construction, before I/O starts
  onReady(() => order.push('ready signal'));
  process.nextTick(() => readyListeners.forEach((listener) => listener()));

  // A timer queued now still lands after every callback above
  setTimeout(() => order.push('timer'), 0);
  setTimeout(() => console.log(order.join(' -> ')), 10);
}, 0);