queueMicrotask Ordering Against Promises And Timers

Schedule callbacks with queueMicrotask and observe that microtasks run in enqueue order after synchronous code but before setTimeout timers get their turn.

JavascriptData Integrity

Code

javascriptsnippet
15 lines
// queueMicrotask: 排进微任务队列——同步代码之后、定时器之前执行
const order = [];

setTimeout(() => order.push('timeout-0'), 0);

Promise.resolve().then(() => order.push('promise-then'));

queueMicrotask(() => order.push('queueMicrotask'));

console.log('sync first');

setTimeout(() => {
  // 微任务按入队顺序清空后,才会执行宏任务
  console.log(order.join(' -> '));
}, 0);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

sync first
promise-then -> queueMicrotask -> timeout-0

How it works

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Top-level bindings order hold the demo state — nothing sits inside a function scope.

Putting it to use

The demo output is labeled (sync first), so every printed line maps back to its originating operation.

Core lines

Promise.resolve().then(() => order.push('promise-then'));
queueMicrotask(() => order.push('queueMicrotask'));
setTimeout(() => order.push('timeout-0'), 0);

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `order`.