Why Microtasks Exist
You'll learn why JavaScript has a separate microtask queue alongside the regular task queue.
The Problem Microtasks Solve
When promises resolve, their callbacks need to run at a predictable time. If promise callbacks went into the regular task queue alongside setTimeout and other async operations, they could be delayed by unrelated events—mouse clicks, timers, I/O operations. This would make promise-based code unpredictable and harder to reason about.
Batching and Consistent Ordering
Microtasks exist to enable batching: all promise resolutions that happen during the current synchronous execution get processed together, in order, before any other async work. This creates a consistent "checkpoint" where all related promise callbacks run.
Think of it like processing urgent memos before moving to the next big task. When you finish a piece of work, you first handle all the quick follow-up notes (microtasks) before starting something completely new (next task).
Why This Matters
Without microtasks, code like this would be unpredictable:
Promise.resolve().then(() => console.log('A'));
Promise.resolve().then(() => console.log('B'));
setTimeout(() => console.log('C'), 0);
Because microtasks run before tasks, you're guaranteed to see A, B, then C. If promises used the task queue, other events could slip between A and B, breaking expectations about execution order.
Microtasks also prevent the "split brain" problem: all synchronously-scheduled promise callbacks complete before the browser re-renders or other tasks run, keeping related updates atomic.
Key Takeaway: Microtasks exist to batch promise callbacks together and ensure they run in consistent, predictable order before any other async operations, making promise-based code reliable and easier to reason about.