JavaScriptHard
How do Promises work internally?
Internally a promise is a small state machine (pending, fulfilled or rejected) with two lists of reactions; settling it stores the result and schedules each registered reaction as a microtask, and every .then call creates a new promise that is resolved with whatever its handler returns.
The internal slots (per the spec)
[[PromiseState]]: pending / fulfilled / rejected.[[PromiseResult]]: the value or reason.[[PromiseFulfillReactions]]and[[PromiseRejectReactions]]: handlers waiting while pending.[[PromiseIsHandled]]: used to report unhandled rejections.
What happens step by step
- Construction: the executor runs synchronously and receives
resolveandrejectfunctions. Only the first call to either has any effect. .then(onFulfilled, onRejected)always returns a new promise. If the original is still pending, the reaction is stored; if already settled, a job is queued immediately.- Settling stores the result and queues every stored reaction as a microtask (a "PromiseReactionJob").
- Running a reaction calls the handler. Its return value resolves the derived promise; a throw rejects it. A missing handler passes the value or error through, which is how errors skip ahead to a later
.catch. - Resolving with a thenable (another promise or any object with a
thenmethod) does not fulfil directly. A job adopts that thenable's eventual state. This "thenable assimilation" is what makes returning promises from.thenflatten chains, and it costs extra microtask ticks.
Why handlers are always async
Even for an already-resolved promise, reactions go through the microtask queue. That guarantees consistent ordering ("Zalgo-free" code).
async/await
await x is roughly "wrap x in a resolved promise and continue the function in a reaction job", which is why code after await always runs in a later microtask.
Code example
js
1// Watching the internals through ordering2const order = [];34const p = new Promise((resolve) => {5 order.push("1 executor runs synchronously");6 resolve("value");7 resolve("ignored"); // only the first settle counts8});910p.then((v) => order.push(`3 reaction ran as a microtask with ${v}`));11order.push("2 .then registered; reaction queued, not run yet");1213// .then returns a NEW promise resolved by the handler's return value14const derived = p.then(() => {15 throw new Error("handler threw");16});17derived.catch((e) => order.push(`4 derived promise rejected: ${e.message}`));18console.log(derived !== p); // true1920// Missing handlers pass values and errors through the chain21Promise.reject(new Error("skips ahead"))22 .then(() => order.push("never runs"))23 .then(() => order.push("never runs either"))24 .catch((e) => order.push(`6 caught later: ${e.message}`)); // needs 3 microtask hops2526// Thenable assimilation: any object with .then is adopted27const thenable = { then(resolve) { resolve("from a thenable"); } };28Promise.resolve(thenable).then((v) => order.push(`5 ${v}`)); // fewer hops, so it lands first2930// Independent chains interleave by how many microtask hops each needs, not by source order.3132await new Promise((r) => setTimeout(r, 0));33console.log(order.join("\n"));
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.