A promise is a state machine: pending, then once either fulfilled with a value or rejected with a reason. The executor gets resolve and reject, and a throw inside it rejects. then registers callbacks, or schedules them if the promise has already settled. To be a real promise, three more things are needed. then returns a new promise resolved with the handler's return value (a throw rejects it), which is what makes chaining work. Handlers always run as microtasks, never synchronously. Resolving with another promise or thenable adopts its outcome. With those in place, await works on your class, and chains interleave in the same order as native promises.
Write a simple promise.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
State, value and a list of callbacks. resolve/reject settle only if still pending, then run the queued callbacks. then queues while pending and calls right away once settled. This passes the phone-screen version, but then doesn't chain and can run synchronously, which real promises never do.
// The core idea: a box that settles once, and runs callbacks when it does.class SimplePromise {constructor(executor) {this.state = 'pending';this.value = undefined;this.callbacks = [];const settle = (state, value) => {if (this.state !== 'pending') return; // a promise settles only oncethis.state = state;this.value = value;this.callbacks.forEach((cb) => cb());};try {executor((value) => settle('fulfilled', value), (reason) => settle('rejected', reason));} catch (error) {settle('rejected', error); // a throwing executor rejects}}then(onFulfilled, onRejected) {const call = () => {if (this.state === 'fulfilled') onFulfilled?.(this.value);else onRejected?.(this.value);};if (this.state === 'pending') this.callbacks.push(call);else call(); // already settled: call now (the next stage makes this async, like real promises)}}
passes 4 checks run on every build, against the native method where there is one
- resolves later, then calls back
- settles only once
- reject, and a throwing executor, call the error callback
- several callbacks on one promise all run, in order
then returns a new promise and wires the handler's outcome into it. A returned value fulfils it, a throw rejects it, and a missing handler passes the outcome through, which is how an error skips to the nearest catch. Every handler runs through queueMicrotask, so code after then() always runs first. The last check runs two interleaved chains on native Promise and on ours and compares the order.
class SimplePromise {#state = 'pending';#value;#handlers = [];constructor(executor) {const settle = (state) => (value) => {if (this.#state !== 'pending') return;this.#state = state;this.#value = value;this.#handlers.forEach((h) => this.#run(h));this.#handlers = [];};try {executor(settle('fulfilled'), settle('rejected'));} catch (error) {settle('rejected')(error);}}// Handlers always run as microtasks, never synchronously inside then().#run({ onFulfilled, onRejected, resolve, reject }) {queueMicrotask(() => {const fulfilled = this.#state === 'fulfilled';const handler = fulfilled ? onFulfilled : onRejected;// No handler for this outcome: pass it down the chain unchanged.if (typeof handler !== 'function') return (fulfilled ? resolve : reject)(this.#value);try {resolve(handler(this.#value)); // the return value feeds the next promise} catch (error) {reject(error); // a throw rejects it}});}// then returns a new promise: that is what makes chains.then(onFulfilled, onRejected) {return new SimplePromise((resolve, reject) => {const h = { onFulfilled, onRejected, resolve, reject };if (this.#state === 'pending') this.#handlers.push(h);else this.#run(h);});}catch(onRejected) {return this.then(undefined, onRejected);}}
passes 6 checks run on every build, against the native method where there is one
- settles only once
- then returns a new promise, so values flow down a chain
- an error skips then handlers until a catch, which can recover
- a throw inside a handler rejects the next promise
- handlers are always async, even on a settled promise
- same order as native promises when chains interleave
If you resolve with something that has a then method, the promise waits for it and takes its outcome. That's how returning a promise from a handler flattens the chain, and why await works on any thenable. The rules from the spec: resolving with yourself is a TypeError, read then only once, call it in a later microtask, and count only its first resolve/reject. finally runs either way, passes the original outcome through, and waits for a promise it returns.
class SimplePromise {#state = 'pending';#value;#handlers = [];constructor(executor) {const [resolve, reject] = this.#resolvers();try {executor(resolve, reject);} catch (error) {reject(error);}}// A resolve/reject pair sharing one flag: only the first call of either counts.#resolvers() {let done = false;return [(value) => { if (!done) { done = true; this.#resolve(value); } },(reason) => { if (!done) { done = true; this.#settle('rejected', reason); } },];}// Resolving with a thenable (another promise, native or ours) adopts its outcome.#resolve(value) {if (value === this) return this.#settle('rejected', new TypeError('A promise cannot resolve to itself'));if (value !== null && (typeof value === 'object' || typeof value === 'function')) {let then;try {then = value.then; // read once: a getter could change between reads} catch (error) {return this.#settle('rejected', error);}if (typeof then === 'function') {const [resolve, reject] = this.#resolvers();queueMicrotask(() => {try {then.call(value, resolve, reject);} catch (error) {reject(error); // ignored if the thenable already resolved}});return;}}this.#settle('fulfilled', value);}#settle(state, value) {if (this.#state !== 'pending') return;this.#state = state;this.#value = value;this.#handlers.forEach((h) => this.#run(h));this.#handlers = [];}#run({ onFulfilled, onRejected, resolve, reject }) {queueMicrotask(() => {const fulfilled = this.#state === 'fulfilled';const handler = fulfilled ? onFulfilled : onRejected;if (typeof handler !== 'function') return (fulfilled ? resolve : reject)(this.#value);try {resolve(handler(this.#value));} catch (error) {reject(error);}});}then(onFulfilled, onRejected) {return new SimplePromise((resolve, reject) => {const h = { onFulfilled, onRejected, resolve, reject };if (this.#state === 'pending') this.#handlers.push(h);else this.#run(h);});}catch(onRejected) {return this.then(undefined, onRejected);}// Runs either way, passes the original outcome through, waits for a promise it returns.finally(onFinally) {return this.then((value) => SimplePromise.resolve(onFinally()).then(() => value),(reason) => SimplePromise.resolve(onFinally()).then(() => { throw reason; }),);}static resolve(value) {return value instanceof SimplePromise ? value : new SimplePromise((resolve) => resolve(value));}static reject(reason) {return new SimplePromise((_, reject) => reject(reason));}}
passes 6 checks run on every build, against the native method where there is one
- await works on it (it's a thenable)
- resolving with a promise adopts its result
- resolving a promise with itself rejects with TypeError
- a misbehaving thenable counts only its first call
- finally passes outcomes through and waits for its own promise
- same order as native when chains interleave
Thenables everywhere
Because await and Promise.resolve adopt any object with a then method, libraries like query builders return thenables that run only when awaited.
Microtask order bugs
Code that assumes a then callback runs synchronously reads state too early. The guarantee that handlers are always async is what makes promise code predictable.
Promises/A+
Before ES2015, libraries like Q, Bluebird and RSVP were made to work together by one spec for then, which is the behaviour this answer follows.
Running
thencallbacks synchronously when the promise is already settled.thenreturningthisinstead of a new promise, so values don't flow down the chain.Letting
resolvebe called twice, orrejectafterresolve.Fulfilling with a promise object instead of adopting it.
Swallowing a throw inside a handler instead of rejecting the next promise.
Why must handlers be asynchronous?
So that code after then() always runs before the handler, whether or not the promise has already settled. Otherwise the same code could run in two different orders, which the Promises/A+ spec calls releasing Zalgo.
How would you add Promise.all on top?
Count settled inputs, store results by index, resolve when the count reaches the length, and reject on the first rejection. There's a full answer to that question in the bank.
What is an unhandled rejection?
A rejected promise with no rejection handler by the time the microtask queue drains. Browsers fire unhandledrejection; Node prints a warning or exits, depending on its flags.