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+)

  1. Executor runs immediately with resolve and reject; if it throws, reject.
  2. Settle once: later calls are ignored.
  3. then(onFulfilled, onRejected) returns a new promise.
  4. Handlers run asynchronously (queueMicrotask), even if already settled.
  5. Return values chain: the handler's return value resolves the next promise; a throw rejects it.
  6. Pass-through: a missing handler forwards the value or error to the next promise.
  7. 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 = [];
5
6 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 }
15
16 #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 once
28 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 }
38
39 #settle(state, value) {
40 if (this.#state !== "pending") return; // settle once
41 this.#state = state;
42 this.#value = value;
43 this.#handlers.forEach((h) => queueMicrotask(h));
44 this.#handlers = [];
45 }
46
47 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-through
52 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 }
61
62 catch(onRejected) {
63 return this.then(undefined, onRejected);
64 }
65
66 finally(fn) {
67 return this.then((v) => MyPromise.resolve(fn()).then(() => v), (r) => MyPromise.resolve(fn()).then(() => { throw r; }));
68 }
69
70 static resolve(v) {
71 return v instanceof MyPromise ? v : new MyPromise((res) => res(v));
72 }
73}
74
75const 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 promise
78 .then((n) => { throw new Error(`failed at ${n}`); })
79 .then(() => "skipped") // pass-through of the rejection
80 .catch((e) => e.message)
81 .finally(() => console.log("finally ran"));
82console.log(result); // failed at 21
83
84// Handlers are async even when already resolved
85const 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.

Open in study app