javascript 55 lines · 10 steps

Building a Promise from scratch

A minimal Promise implementation showing how state, microtasks, and chaining fit together.

Explained by highlit
1const PENDING = 'pending';
2const FULFILLED = 'fulfilled';
3const REJECTED = 'rejected';
4 
5class MyPromise {
6 constructor(executor) {
7 this.state = PENDING;
8 this.value = undefined;
9 this.callbacks = [];
10 const resolve = (value) => this.settle(FULFILLED, value);
11 const reject = (reason) => this.settle(REJECTED, reason);
12 try {
13 executor(resolve, reject);
14 } catch (err) {
15 reject(err);
16 }
17 }
18 
19 settle(state, value) {
20 if (this.state !== PENDING) return;
21 this.state = state;
22 this.value = value;
23 this.callbacks.forEach((cb) => this.schedule(cb));
24 this.callbacks = [];
25 }
26 
27 schedule(cb) {
28 queueMicrotask(() => cb(this.state, this.value));
29 }
30 
31 then(onFulfilled, onRejected) {
32 return new MyPromise((resolve, reject) => {
33 const handle = (state, value) => {
34 const handler = state === FULFILLED ? onFulfilled : onRejected;
35 if (typeof handler !== 'function') {
36 state === FULFILLED ? resolve(value) : reject(value);
37 return;
38 }
39 try {
40 const result = handler(value);
41 if (result instanceof MyPromise) result.then(resolve, reject);
42 else resolve(result);
43 } catch (err) {
44 reject(err);
45 }
46 };
47 if (this.state === PENDING) this.callbacks.push(handle);
48 else this.schedule(handle);
49 });
50 }
51 
52 catch(onRejected) {
53 return this.then(undefined, onRejected);
54 }
55}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A promise is a small state machine that transitions from pending to a single terminal state exactly once.
  2. 2Callbacks registered before settlement are queued, and resolution always runs asynchronously via the microtask queue.
  3. 3then returns a new promise whose fate is decided by the handler's return value, enabling chains and flattening nested promises.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a Promise from scratch — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code