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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A promise is a small state machine that transitions from pending to a single terminal state exactly once.
- 2Callbacks registered before settlement are queued, and resolution always runs asynchronously via the microtask queue.
- 3then returns a new promise whose fate is decided by the handler's return value, enabling chains and flattening nested promises.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-promise-from-scratch-explained-javascript-bdfe/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.