JavaScriptHard
Implement a simple Promise
A minimal Promise is a state machine (pending, fulfilled, rejected) with queued handlers: resolve/reject settle it once and run the handlers as microtasks, and then returns a new promise resolved by the handler's result, adopting it if the result is itself a thenable.
Core requirements (Promises/A+)
- Executor runs immediately with
resolveandreject; if it throws, reject. - Settle once: later calls are ignored.
then(onFulfilled, onRejected)returns a new promise.- Handlers run asynchronously (
queueMicrotask), even if already settled. - Return values chain: the handler's return value resolves the next promise; a throw rejects it.
- Pass-through: a missing handler forwards the value or error to the next promise.
- Thenable assimilation: resolving with a promise or thenable adopts its eventual state (and guards against a promise resolving with itself).
Extras to add if time allows
catch (then(undefined, onRejected)), finally (runs a callback, passes the original result through), and static helpers resolve, reject, all, race.
What this demonstrates
Understanding of closures, microtasks, recursion through thenables, and why await always continues asynchronously. Real engines implement the same algorithm natively.
Code example
js
1class MyPromise {2 #state = "pending";3 #value;4 #handlers = [];56 constructor(executor) {7 const resolve = (value) => this.#resolve(value);8 const reject = (reason) => this.#settle("rejected", reason);9 try {10 executor(resolve, reject);11 } catch (err) {12 reject(err);13 }14 }1516 #resolve(value) {17 if (this.#state !== "pending") return;18 if (value === this) return this.#settle("rejected", new TypeError("Cannot resolve a promise with itself"));19 if (value && (typeof value === "object" || typeof value === "function")) {20 let then;21 try {22 then = value.then;23 } catch (err) {24 return this.#settle("rejected", err);25 }26 if (typeof then === "function") {27 let called = false; // a thenable may call back only once28 try {29 then.call(value, (v) => !called && ((called = true), this.#resolve(v)), (r) => !called && ((called = true), this.#settle("rejected", r)));30 } catch (err) {31 if (!called) this.#settle("rejected", err);32 }33 return;34 }35 }36 this.#settle("fulfilled", value);37 }3839 #settle(state, value) {40 if (this.#state !== "pending") return; // settle once41 this.#state = state;42 this.#value = value;43 this.#handlers.forEach((h) => queueMicrotask(h));44 this.#handlers = [];45 }4647 then(onFulfilled, onRejected) {48 return new MyPromise((resolve, reject) => {49 const handle = () => {50 const cb = this.#state === "fulfilled" ? onFulfilled : onRejected;51 if (typeof cb !== "function") return (this.#state === "fulfilled" ? resolve : reject)(this.#value); // pass-through52 try {53 resolve(cb(this.#value));54 } catch (err) {55 reject(err);56 }57 };58 this.#state === "pending" ? this.#handlers.push(handle) : queueMicrotask(handle);59 });60 }6162 catch(onRejected) {63 return this.then(undefined, onRejected);64 }6566 finally(fn) {67 return this.then((v) => MyPromise.resolve(fn()).then(() => v), (r) => MyPromise.resolve(fn()).then(() => { throw r; }));68 }6970 static resolve(v) {71 return v instanceof MyPromise ? v : new MyPromise((res) => res(v));72 }73}7475const result = await new MyPromise((resolve) => setTimeout(() => resolve(2), 10))76 .then((n) => n * 10)77 .then((n) => new MyPromise((res) => res(n + 1))) // adopts the returned promise78 .then((n) => { throw new Error(`failed at ${n}`); })79 .then(() => "skipped") // pass-through of the rejection80 .catch((e) => e.message)81 .finally(() => console.log("finally ran"));82console.log(result); // failed at 218384// Handlers are async even when already resolved85const order = [];86MyPromise.resolve("x").then(() => order.push("handler"));87order.push("sync");88await null;89await null;90console.log(order); // ["sync", "handler"]
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.