liveBook · Manning

Microtask queue

As explained in Build a Frontend Web Framework (From Scratch)

A microtask queue is the event-loop queue that stores microtasks for execution after the current synchronous code and before later task processing.

A microtask queue stores promise callbacks until the current synchronous JavaScript finishes. The event loop then moves queued callbacks onto the execution stack before it processes the next task, such as an event-handler callback. section 13.3.2

The simplified event-loop cycle handles the queue in this order:

  • Execute every microtask in order, including microtasks added while earlier microtasks are running. section 13.3.3
  • Execute the oldest task that was already present when the cycle began. section 13.3.3
  • Allow the browser to render pending DOM changes, then begin another cycle while tasks remain. section 13.3.3

Async mounting callback

An async onMounted() hook runs synchronously until await fetch(...). The remaining statements—such as updating data and clearing loading—become a promise callback in the microtask queue. The mounting process continues first, so the component may be interactive before that callback runs. section 13.3.1

Promise syntax made visible

The same behavior can be written with fetch(...).then((data) => { ... }). The code before .then() executes immediately; the callback passed to .then() is deferred to the microtask queue. section 13.3.1

Figure 13.5 Execute all the microtasks in the microtask queue.
figure

Use the event-loop figure to trace the point at which all pending microtasks execute before the oldest task. section 13.3.3

Because microtasks run before the next task and block JavaScript while executing, a long or poorly sequenced microtask chain can delay user interaction. This ordering also lets a scheduler defer lifecycle work until mounting has progressed. section 13.3.3 section 13.5

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Explains queue ordering, newly added microtasks, task comparison, rendering, and execution-stack transfer, without implementing a browser event loop.
Examples
Uses async onMounted(), fetch(), await, and then() to show synchronous prefixes and deferred promise callbacks.
What it assumes
Assumes basic JavaScript functions and promises while defining the execution stack, tasks, microtasks, and event loop.
What you can do after
Diagnose asynchronous lifecycle sequencing by predicting when promise callbacks run relative to mounting, tasks, interaction, and rendering.
How it connects
Connects promise callbacks with the execution stack, task queue, event loop, asynchronous functions, and lifecycle hooks.

Also explained in

Compare how 2 books explain microtask queue →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.