queueMicrotask Orders Against Promise Then
queueMicrotask callbacks run after the current task in FIFO order interleaved with promise reactions, so all microtasks drain before any timer fires.
Code
export {};
const order: string[] = [];
queueMicrotask(() => order.push('microtask-1'));
setTimeout(() => order.push('timeout'), 0);
Promise.resolve().then(() => order.push('promise-then'));
queueMicrotask(() => order.push('microtask-2'));
// 当前任务结束先清空微任务队列:microtask-1 与 promise-then 按 FIFO 交错
await Promise.resolve();
console.log('after microtasks:', order.join(','));
// 定时器是宏任务,要等微任务队列彻底排空才轮到它
setTimeout(() => console.log('after macrotask:', order.join(',')), 10);Output
Captured from a sandboxed run of this snippet in the build pipeline.
after microtasks: microtask-1,promise-then,microtask-2
after macrotask: microtask-1,promise-then,microtask-2,timeoutThe order things happen in
The queueMicrotask and setTimeout callbacks are never awaited; the single await Promise.resolve() only yields the current turn, and the printed order shows the microtask queue draining FIFO before the timer runs.
What to watch for
- The toolchain suffices on its own — dependency resolution never runs.
Using it
The run prints after microtasks:, after macrotask: — each prefix names the step that produced it.
Key statements
Promise.resolve().then(() => order.push('promise-then'));
await Promise.resolve();
queueMicrotask(() => order.push('microtask-1'));
Interactive Tools for This Topic
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit.
Report a problem with this exampleOpens a pre-filled issue on GitHub.