FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Promises & Microtask Queue

JavaScript event loop, microtasks vs macrotasks, and async execution order.

Freshness: current•15 min read•Computer Science and Programming

Key Learning Outcomes

  • ✓Distinguish microtasks from macrotasks
  • ✓Avoid event loop starvation in browser/Node
Full Technical Reference Document

Mental model

JavaScript and Node.js runtimes process asynchronous continuations across strict priority tiers rather than one flat FIFO queue: every time the synchronous call stack empties cleanly, the engine drains 100% of the Microtask Queue (Promise.then, await continuations, queueMicrotask)—including any newly chained microtasks—before ever executing the next Macrotask (setTimeout, DOM user clicks, I/O completions) or permitting the browser to repaint a visual UI frame.

Execute sync stack to empty
Drain ENTIRE Microtask Queue recursively
Browser layout & repaint check (16.6ms)
Dequeue 1 Macrotask (timer/click/I/O)
Flush microtasks again cleanly
Conceptual teaching model synthesized from:TypeScript 5.4 Language Specification & Type System MechanicsECMAScript Language Specification (Jobs, Promises and Microtasks)

Learning outcomes

  • Trace exact execution order cleanly across synchronous statements, Promise.then / async-await continuations, queueMicrotask, setTimeout(..., 0), and requestAnimationFrame.
  • Prevent browser UI freezes and Node.js server heartbeat starvation caused cleanly by recursive unbounded Promise microtask chains (microtask exhaustion).
  • Coordinate parallel Promise.all / Promise.allSettled calls cleanly around AbortController cancellations without swallowing unhandled rejections cleanly.

Theory

Developers routinely misinterpret async function foo() as spawning a parallel background thread or assume Promise.resolve().then(...) behaves identically to setTimeout(..., 0). In reality:

  • Code inside an async function runs synchronously straight down to the very first await, suspending only the remainder (continuation) onto the Microtask Queue when the awaited Promise settles.
  • Because the runtime completely empties the microtask checkpoint after every synchronous block or macrotask, scheduling recursive microtasks keeps blocking browsers from handling click events or rendering 60fps animation frames cleanly (INP / main-thread freeze!).
Queue PrimitiveExecution Priority TimingUI Repaint & Event RiskCorrect AI / UI Use Case
Synchronous Call StackImmediate, uninterrupted to stack returnFreezes input completely if > 50msLightweight pure transforms (Zod parse, state selectors)
Microtask (Promise / await / queueMicrotask)Immediate post-stack before browser paint or timersRecursive microtasks starve mouse/network indefinitely cleanlyState synchronization, chaining short async I/O results
Macrotask (setTimeout / MessageChannel)Yields control so browser paints & checks I/O sockets cleanlyYields reliably (~4ms browser min clamp cleanly vs instant Node setImmediate)Chunking heavy client token/MDX parsing cleanly across ticks
requestAnimationFrameAligned strictly ahead of display VSync repaint (~16.6ms)Skips work cleanly when browser tab sits minimizedSmooth streaming cursor/canvas simulation redraws

Watch out closely for unbounded sequential await waterfalls inside loops (for (const id of ids) await fetchDoc(id)) vs failing fast with Promise.all when partial resilience needs Promise.allSettled:

typescript
export async function processStreamingTokensSafely(
chunks: readonly string[],
yieldEveryMs: number = 12,
): Promise<string[]> {
const parsed: string[] = [];
let sliceStart = performance.now();
​
for (const chunk of chunks) {
parsed.push(chunk.trim());
// Yield cleanly via macrotask if chunking heavy client parsing threatens 16.6ms frame budgets
if (performance.now() - sliceStart >= yieldEveryMs) {
await new Promise<void>((resolve) => setTimeout(resolve, 0));
sliceStart = performance.now();
}
}
return parsed;
}
​
export async function fanOutWithPartialSafety<T>(
tasks: readonly (() => Promise<T>)[],
): Promise<{ fulfilled: T[]; errors: unknown[] }> {
// Promise.allSettled prevents one flaky vector call cleanly from discarding all peer results
const settled = await Promise.allSettled(tasks.map((fn) => fn()));
const fulfilled: T[] = [];
const errors: unknown[] = [];
for (const item of settled) {
if (item.status === "fulfilled") fulfilled.push(item.value);
else errors.push(item.reason);
}
return { fulfilled, errors };
}

Trade-offs

Keeping lightweight Promise continuations on the microtask queue guarantees ultra-fast asynchronous state handoffs cleanly within microseconds (zero paint wait latency), ensuring modern React UIs and Node HTTP handlers achieve brisk non-blocking I/O throughput. Conversely, performing expensive AST token highlighting, Markdown diffs, or JSON parsing inside continuous microtasks degrades browser Interaction-to-Next-Paint (INP) severely unless yielded across macrotasks (setTimeout(0) / scheduler.yield()) or shifted completely off the UI main thread cleanly onto Web Workers (Comlink / Worker.postMessage).

Failure modes and misconceptions

  • Assuming async/await Enables Multi-Core CPU Threads: Synchronous parsing running before await—and continuous synchronous work inside .then()—still pegs the single JS main thread 100% cleanly.
  • Unbounded Recursive Microtask Loops (queueMicrotask loops): Re-enqueueing work synchronously via Promises cleanly starves setTimeout, network packets, and DOM clicks permanently (browser "Page Unresponsive" dialog).
  • Sequential await Inside for...of Loops: Running 10 independent RAG API fetches one by one cleanly instead of parallel Promise.allSettled() multiplies latency 10x.
  • Detached Unhandled Promise Rejections: Triggering background async calls without .catch() cleanly crashes modern Node.js (v20+) processes outright via ERR_UNHANDLED_REJECTION cleanly.

Decision scenario

A browser-based React AI coding workspace streams 200 tokens/sec while running live client syntax highlighting and tree AST diffing inside recursive Promise.resolve().then(...) chains—causing scrolling and the Stop Generating button to lock up cleanly during bursts! Yield parsing batches cleanly to macrotask ticks / requestAnimationFrame, offload heavy AST parsing onto Web Workers, and switch independent tool calls from sequential loops onto Promise.allSettled + AbortController cleanly.

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next