Skip to content
Astera Technology

Predict synchronous code and queued microtasks

Trace a resolved promise reaction and queueMicrotask after synchronous work.

Download complete case notes and answer keys ↓

Trace the fixed program

The trace starts with start. Schedule a promise reaction, then queueMicrotask, then append end synchronously. The final promise reaction prints the completed trace.

Complete original program
const trace=['start'];
Promise.resolve().then(()=>trace.push('promise'));
queueMicrotask(()=>trace.push('microtask'));
trace.push('end');
Promise.resolve().then(()=>console.log(JSON.stringify(trace)));
Exact console output
["start","end","promise","microtask"]
Values and execution
Execution stageAdded valueTrace at that point
Synchronous bodystart, end["start","end"]
First queued reactionpromise["start","end","promise"]
Explicit microtaskmicrotask["start","end","promise","microtask"]

Explain the result

The synchronous body finishes before these queued callbacks run. In this supplied sequence the promise reaction is enqueued before the explicit microtask. The printing reaction follows both. This observes queue order, not elapsed time or scheduling across unrelated tasks and hosts.

Test the alternative

Reading a flag immediately after .then sees false even on an already fulfilled promise. A later reaction sees true.

Separate finite alternative
let ran=false;Promise.resolve().then(()=>{ran=true;});const immediate=ran;
Promise.resolve().then(()=>console.log(JSON.stringify({immediate,later:ran})));
Alternative output
{"immediate":false,"later":true}

Work the boundary case

If queueMicrotask is scheduled first, what changes?

Show the worked answer

The two queued labels swap. start and end still precede both in this program.

Fresh boundary program
const trace=['start'];queueMicrotask(()=>trace.push('microtask'));Promise.resolve().then(()=>trace.push('promise'));trace.push('end');
Promise.resolve().then(()=>console.log(JSON.stringify(trace)));
Boundary output
["start","end","microtask","promise"]

Original example files