← Back to Node.js, page 10

nodejs-0197 · Hard senior

Implement a minimal Promise class (then, catch, finally, resolve, reject) that follows the main rules of Promises/A+. How does asynchronous chaining work?

A promise has a state (pending, fulfilled, rejected), a value, and a list of handlers. It settles once. then registers handlers and returns a new promise, handlers always run asynchronously (queueMicrotask), and the value returned by a handler resolves the new promise through the resolution procedure: a promise or thenable is adopted, a plain value fulfils, a thrown error rejects, and resolving with the promise itself is a TypeError.

Full answer

State

  • state: pending, fulfilled or rejected. value: the result or the reason. handlers: callbacks waiting for settlement. Once settled, the state and value never change.

Constructor

  • Call executor(resolve, reject) in a try/catch. A throw rejects the promise. resolve and reject work only once (guard with a flag).

The resolution procedure resolve(x)

  • If x is the promise itself, reject with a TypeError (a chaining cycle).
  • If x is an object or function with a then method (a thenable, including real promises), call x.then with resolve and reject functions that again follow the procedure, and use the once-only guard. Errors while reading or calling then reject.
  • Otherwise fulfil with x.

then(onFulfilled, onRejected)

  • Returns a new promise. Store a handler record with the callbacks and the resolve and reject of the new promise. If the promise is already settled, schedule the handlers right away.
  • Handlers run asynchronously with queueMicrotask, even when the promise is already settled. If a callback is not a function, pass the value or reason through to the next promise.
  • The callback result goes to the new promise's resolve (through the procedure above). A throw in the callback rejects the new promise.

Helpers

  • catch(fn) is then(undefined, fn). finally(fn) runs fn and passes the original result or reason through, unless fn throws or returns a rejected promise.
  • Static resolve and reject create settled promises.

Real promises have extra features (species, internal slots, exact tick counts for await), so this is a teaching model. The official test suite promises-aplus-tests can check an implementation.

javascript
const PENDING = 0, FULFILLED = 1, REJECTED = 2;

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

  constructor(executor) {
    let called = false;
    const resolve = (x) => { if (!called) { called = true; this.#resolveWith(x); } };
    const reject = (reason) => { if (!called) { called = true; this.#settle(REJECTED, reason); } };
    try { executor(resolve, reject); } catch (err) { reject(err); }
  }

  #resolveWith(x) {
    if (x === this) return this.#settle(REJECTED, new TypeError('Chaining cycle detected'));
    if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
      let then;
      try { then = x.then; } catch (err) { return this.#settle(REJECTED, err); }
      if (typeof then === 'function') {
        let called = false;
        try {
          then.call(x,
            (y) => { if (!called) { called = true; this.#resolveWith(y); } },
            (r) => { if (!called) { called = true; this.#settle(REJECTED, r); } });
        } catch (err) { if (!called) { called = true; this.#settle(REJECTED, err); } }
        return;
      }
    }
    this.#settle(FULFILLED, x);
  }

  #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') return (this.#state === FULFILLED ? resolve : reject)(this.#value);
    try { resolve(callback(this.#value)); } catch (err) { reject(err); }
  }

  then(onFulfilled, onRejected) {
    return new MyPromise((resolve, reject) => {
      this.#handlers.push({ onFulfilled, onRejected, resolve, reject });
      this.#flush();
    });
  }
  catch(onRejected) { return this.then(undefined, onRejected); }
  finally(fn) {
    return this.then(
      (value) => MyPromise.resolve(fn()).then(() => value),
      (reason) => MyPromise.resolve(fn()).then(() => { throw reason; }));
  }
  static resolve(x) { return x instanceof MyPromise ? x : new MyPromise((resolve) => resolve(x)); }
  static reject(reason) { return new MyPromise((_, reject) => reject(reason)); }
}

(async () => {
  // 1. Handlers run asynchronously, and interleave with native promises one step at a time.
  const log = [];
  Promise.resolve().then(() => log.push('native 1')).then(() => log.push('native 2'));
  MyPromise.resolve().then(() => log.push('mine 1')).then(() => log.push('mine 2'));
  log.push('sync');
  await new Promise((r) => setTimeout(r, 10));
  console.log('1.', log.join(', '));

  // 2. Chaining: values, thrown errors, thenables and native promises are all adopted.
  const chained = await MyPromise.resolve(1).then((n) => n + 1).then((n) => Promise.resolve(n * 10)).then((n) => ({ then: (ok) => ok(n + 5) }));
  console.log('2. chained value:', chained);
  console.log('3. error path   :', await MyPromise.resolve().then(() => { throw new Error('bad'); }).catch((e) => 'caught ' + e.message).finally(() => {}));

  // 4. Settles once; executor throw rejects; cycle is a TypeError.
  console.log('4. settle once  :', await new MyPromise((resolve, reject) => { resolve('first'); resolve('second'); reject(new Error('ignored')); }));
  console.log('   executor throw:', await new MyPromise(() => { throw new Error('in executor'); }).catch((e) => e.message));
  const cyclic = MyPromise.resolve().then(() => cyclic);
  console.log('   cycle         :', await cyclic.catch((e) => e.constructor.name));

  // 5. await works on it, because it has a then method.
  console.log('5. awaited      :', await new MyPromise((resolve) => setTimeout(resolve, 5, 'done')));
  console.log('6. finally passes the value on:', await MyPromise.resolve('kept').finally(() => 'ignored'));
})();

A teaching model, not a replacement for the built-in Promise. It was checked with the cases in the script only, not with the promises-aplus-tests suite. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. sync, native 1, mine 1, native 2, mine 2 2. chained value: 25 3. error path : caught bad 4. settle once : first executor throw: in executor cycle : TypeError 5. awaited : done 6. finally passes the value on: kept

Key points

  • Settle once; keep state and value.
  • then returns a new promise and always runs handlers asynchronously.
  • The resolution procedure adopts thenables.
  • A throw in a handler rejects the next promise.
  • catch and finally are built on then.

Common mistakes

  • Running handlers synchronously when the promise is already settled.
  • Not guarding resolve and reject against being called twice.
  • Forgetting to adopt thenables, so promises are not flattened.
  • Letting the same promise be resolved with itself.
  • Calling handlers of one then in the wrong order.

Follow-ups

  • Why must then handlers run asynchronously?
  • How does await use the then method?
  • What are unhandled rejections in this model?

Tips

  • Describe the state machine first.
  • Explain the resolution procedure.
  • Say that this is for learning.