Skip to content
jshacks.dev
Functions

Implement a Promise From Scratch in JavaScript

Implement a Promise from scratch in JavaScript with states, then chaining, microtask timing, thenable resolution and rejection, and the Promises/A+ rules.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm and TypeScript logos.

A promise is an object that stands for a value that is not available yet. Writing one from scratch is the hardest of the common JavaScript interview questions, and also one of the most instructive: it forces you to build state, callbacks, chaining, error propagation and the timing rule that then callbacks never run synchronously. This post builds a small MyPromise class on Node.js 24 in stages, each with its output, following the rules of the Promises/A+ specification that matter in practice. It does not implement every rule of the specification, and it says where it stops. Related questions on this site are implementing Promise.all and implementing Promise.race.

The model

A promise is in one of three states: pending, fulfilled with a value, or rejected with a reason. It starts pending and settles once. After that it never changes. You attach handlers with then(onFulfilled, onRejected), which returns a new promise, so calls can be chained. Handlers run asynchronously, after the current synchronous code finishes, and in the order they were attached.

Stage 1: state and the constructor

The constructor takes an executor function and calls it at once with two functions, resolve and reject.

JavaScript
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

class MyPromise {
  #state = PENDING;
  #value;
  #handlers = [];

  constructor(executor) {
    const resolve = (value) => this.#settle(FULFILLED, value);
    const reject = (reason) => this.#settle(REJECTED, reason);

    try {
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }

  #settle(state, value) {
    if (this.#state !== PENDING) {
      return;
    }

    this.#state = state;
    this.#value = value;
    this.#flush();
  }

  #flush() {}

  get state() {
    return this.#state;
  }
}

const first = new MyPromise((resolve) => resolve(1));
const second = new MyPromise((resolve, reject) => {
  resolve("a");
  reject(new Error("ignored"));
  resolve("b");
});
const third = new MyPromise(() => {
  throw new Error("boom");
});

console.log(first.state, second.state, third.state);
Text
fulfilled fulfilled rejected

The guard in #settle makes the first call win, so the later reject and resolve in second do nothing. An exception thrown by the executor rejects the promise, which is why third is rejected. The private fields keep the state out of reach: nobody can change a promise's state from outside, which is part of the contract.

The then method comes next, and it has to deal with the case where the promise is still pending, so handlers are stored and run later.

Stage 2: then, handlers and asynchronous delivery

The class below is the complete version of the stage 1 class, so use it in place of the earlier one. then creates a new promise. When the current promise settles, the right handler runs, and its result decides the new promise. The key rule: handlers run asynchronously, even if the promise is already settled. queueMicrotask gives the same timing as native promises.

JavaScript
class MyPromise {
  #state = "pending";
  #value;
  #handlers = [];

  constructor(executor) {
    const resolve = (value) => this.#resolveWith(value);
    const reject = (reason) => this.#settle("rejected", reason);

    try {
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }

  #settle(state, value) {
    if (this.#state !== "pending") {
      return;
    }

    this.#state = state;
    this.#value = value;
    this.#flush();
  }

  #flush() {
    if (this.#state === "pending") {
      return;
    }

    const handlers = this.#handlers;
    this.#handlers = [];

    for (const handler of handlers) {
      queueMicrotask(() => this.#run(handler));
    }
  }

  #run({ onFulfilled, onRejected, resolve, reject }) {
    const callback = this.#state === "fulfilled" ? onFulfilled : onRejected;

    if (typeof callback !== "function") {
      if (this.#state === "fulfilled") {
        resolve(this.#value);
      } else {
        reject(this.#value);
      }

      return;
    }

    try {
      resolve(callback(this.#value));
    } catch (error) {
      reject(error);
    }
  }

  #resolveWith(value) {
    resolveValue(
      this,
      value,
      (plain) => this.#settle("fulfilled", plain),
      (reason) => this.#settle("rejected", reason),
    );
  }

  then(onFulfilled, onRejected) {
    return new MyPromise((resolve, reject) => {
      this.#handlers.push({ onFulfilled, onRejected, resolve, reject });
      this.#flush();
    });
  }

  catch(onRejected) {
    return this.then(undefined, onRejected);
  }
}

const log = [];

const p = new MyPromise((resolve) => resolve(10));

p.then((n) => log.push(`then ${n}`));
log.push("sync after then");

await new Promise((resolve) => setTimeout(resolve, 0));

console.log(log);
Text
[ 'sync after then', 'then 10' ]

Even though p is already fulfilled, the handler runs after the synchronous line, because #flush schedules it with queueMicrotask. This guarantee prevents a class of bugs where code behaves differently depending on whether a value was already available. The #resolveWith method hands the value to resolveValue, a helper that stage 4 defines. It is a function declaration, so it is available to the class above it.

Three more rules are built into #run. If a handler is missing, the value or reason is passed through to the next promise, which is why p.then().then(f) still reaches f. A handler's return value resolves the new promise. And an exception inside a handler rejects the new promise, instead of escaping.

Stage 3: chaining and error propagation

JavaScript
const chained = new MyPromise((resolve) => resolve(2))
  .then((n) => n * 10)
  .then((n) => {
    throw new Error(`failed at ${n}`);
  })
  .then(() => "skipped")
  .catch((error) => `recovered: ${error.message}`)
  .then((text) => text.toUpperCase());

const results = [];

chained.then((value) => results.push(value));

await new Promise((resolve) => setTimeout(resolve, 0));

console.log(results);
Text
[ 'RECOVERED: FAILED AT 20' ]

The value 2 becomes 20, then the handler throws, so the next then without a rejection handler passes the rejection along, and catch converts it into a normal value, which the last then transforms. Errors skip fulfillment handlers until something handles them, as with native promises.

Stage 4: resolving with a promise or thenable

So far, a handler that returns a promise would fulfill the new promise with the promise object itself, not with its value. The specification says that resolving with a thenable, an object with a then method, must adopt its state. This is what makes then(() => fetchSomething()) work.

JavaScript
function resolveValue(promise, value, resolve, reject) {
  if (value === promise) {
    reject(new TypeError("Chaining cycle detected for promise"));
    return;
  }

  if (value !== null && (typeof value === "object" || typeof value === "function")) {
    let then;

    try {
      then = value.then;
    } catch (error) {
      reject(error);
      return;
    }

    if (typeof then === "function") {
      let called = false;

      try {
        then.call(
          value,
          (inner) => {
            if (!called) {
              called = true;
              resolveValue(promise, inner, resolve, reject);
            }
          },
          (reason) => {
            if (!called) {
              called = true;
              reject(reason);
            }
          },
        );
      } catch (error) {
        if (!called) {
          called = true;
          reject(error);
        }
      }

      return;
    }
  }

  resolve(value);
}

This is the resolution procedure from the specification, simplified. It rejects a cycle, reads then once inside a try because a getter can throw, calls it with one-shot callbacks guarded by called, resolves recursively because the inner value may be another thenable, and otherwise fulfills with the plain value. The called flag handles thenables that call both callbacks, or call one twice, which the specification says must be ignored.

With #resolveWith calling this helper, a handler can return a promise or any thenable, and the next step receives the unwrapped value.

JavaScript
const delayed = (value, ms) => new MyPromise((resolve) => setTimeout(() => resolve(value), ms));

const order = [];

await delayed("a", 5)
  .then((value) => {
    order.push(value);
    return delayed("b", 5);
  })
  .then((value) => {
    order.push(value);
    return { then: (resolve) => resolve("c") };
  })
  .then((value) => order.push(value));

console.log(order);
Text
[ 'a', 'b', 'c' ]

The second handler returns a MyPromise that settles later, and the third returns a plain object with a then method. In both cases the next handler gets the final value, not the promise or the object. await works on our class too, because await treats any object with a then method as a thenable and calls it.

Static helpers

Promise.resolve and Promise.reject are short.

JavaScript
MyPromise.resolve = (value) => new MyPromise((resolve) => resolve(value));
MyPromise.reject = (reason) => new MyPromise((_, reject) => reject(reason));

The combinators, all, race, allSettled and any, are covered in their own posts, starting with Promise.all.

What the Promises/A+ test suite checks

The official suite has a few hundred tests. The ones that most often fail in student implementations are the asynchronous delivery of handlers, the guarantee that handlers run in the order they were attached, the called guard in thenable resolution, passing a non-function handler through, and the cycle check. If you implement these, you pass the bulk of the suite. The specification also says that a handler is called with no this, and a fulfilled promise's value is never changed, so the same value reaches every handler.

What this version leaves out

A few things are missing on purpose. There is no finally, which is then with a handler that ignores the value and passes the original result through. There is no unhandled rejection tracking: Node.js reports a rejected promise that has no handler by default and ends the process with an error since version 15, and a class would need its own bookkeeping to match. And the timing of await with a custom thenable differs from a native promise by one or more microtask ticks, so ordering between a native promise and ours can differ in subtle ways.

Tests

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("then callbacks run asynchronously", async () => {
  const log = [];
  const p = new MyPromise((resolve) => resolve(1));

  p.then(() => log.push("then"));
  log.push("sync");

  await new Promise((resolve) => setTimeout(resolve, 0));

  assert.deepEqual(log, ["sync", "then"]);
});

test("a rejection skips fulfillment handlers until caught", async () => {
  const seen = [];

  await new MyPromise((_, reject) => reject(new Error("x")))
    .then(() => seen.push("skipped"))
    .catch((error) => seen.push(error.message));

  assert.deepEqual(seen, ["x"]);
});
Text
ℹ tests 2
ℹ pass 2
ℹ fail 0

How to present it

Say the model first: three states, settle once, then returns a new promise, handlers run asynchronously. Write the state and constructor in a few lines, then then. Do not start with thenable resolution: build the chain with plain values first, show that it works, and only then say that returning a promise from a handler requires the resolution procedure. That order mirrors how the specification is layered and keeps the interviewer following.

Finish by saying what you would not do in production: use the native Promise, which is faster, integrated with await and checked for unhandled rejections. The exercise teaches the contract, and the contract is what matters when you debug an ordering problem.

Also inAsync
Taggedinterview
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.