codecks.

Async & promises · Output question

JavaScript Promise executor timing

A Promise constructor has its own log and a later reaction. Predict which parts run immediately and which wait.

const ready = new Promise(resolve => {
  console.log("build");
  resolve("done");
});
ready.then(value => console.log(value));
console.log("after");

What gets logged?

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

  1. after
    build
    done
  2. build
    done
    after
  3. build
    after
    done
  4. done
    build
    after
Reveal the answer and execution trace
build
after
done

A Promise executor runs synchronously. Its then callback runs later as a microtask.

  1. Line 2. Constructing the Promise calls the executor immediately and logs "build".
  2. Line 3. resolve fulfills the promise.
  3. Line 5. then queues its callback for a later microtask.
  4. Line 6. The script logs "after", then the queued callback logs "done".

Reference: Promise constructor on MDN.