codecks.

Async & promises · Output question

JavaScript promises, timers, and synchronous output

A promise reaction and a zero-delay timer are scheduled beside synchronous logs. Predict which queued callback runs first.

console.log("open");
setTimeout(() => console.log("timer"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("close");

What gets logged?

Choose an output before opening the walkthrough, or check your answer in practice mode.

  1. open
    timer
    promise
    close
  2. open
    close
    promise
    timer
  3. open
    promise
    close
    timer
  4. open
    close
    timer
    promise
Reveal the answer and execution trace
open
close
promise
timer

The current script finishes, then the promise reaction runs as a microtask, then the timer callback runs as a task.

  1. Line 1. The script logs "open" immediately.
  2. Line 2. The timer callback is scheduled for a later task.
  3. Line 3. The fulfilled promise schedules a reaction microtask.
  4. Line 4. The script logs "close". After the script ends, the promise runs before the timer.

Reference: Tasks and microtasks on MDN.