实现说明
整个示例围绕函数 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);