Microtasks vs Tasks

Promise reactions and queueMicrotask() use the microtask queue. Timers and many host callbacks are scheduled as tasks. After the current JavaScript job completes, the runtime processes available microtasks before moving on to another task.

This is why a resolved Promise can run before a zero-delay timer.

Promise vs setTimeout
console.log('A');

setTimeout(() => {
  console.log('B');
}, 0);

Promise.resolve().then(() => {
  console.log('C');
});

console.log('D');
💡 The synchronous logs A and D execute first. The Promise reaction is processed as a microtask before the timer task, producing C before B.
Key Takeaways
  • Synchronous code runs before queued asynchronous callbacks.
  • Promise reactions are microtasks.
  • Microtasks are processed before the runtime proceeds to another task.
Knowledge Check

What is the output order of the example?