Skip to the page

Polyfills interviewers ask · senior

Build a Promise from scratch

A minimal Promise is a state machine (pending -> fulfilled or rejected, once) with a list of handlers; then returns a new promise that resolves with the handler's return value (adopting thenables) or rejects if the handler throws, and every handler runs asynchronously via queueMicrotask.

The notes

What you must know

  • Fields: state, value, handlers. resolve and reject do nothing if the state is no longer pending.
  • Call the executor synchronously inside try/catch; a throw rejects.
  • then(onFulfilled, onRejected) returns a new promise. If the current promise is pending, store a handler; otherwise schedule it. Every handler runs inside queueMicrotask, even for already-settled promises.
  • If a handler is missing, pass the value forward or rethrow the reason.
  • Resolution procedure: resolving with itself is a TypeError; if x is a thenable (object or function with a then method), call its then once with guarded resolve/reject; otherwise fulfill with x.
  • Then add catch (then(undefined, fn)), finally and the statics resolve, reject and all.
  • Follow-ups seen in interviews: then after the promise already settled, several thens on one promise, and cancel() for a promise backed by an XHR (Dream11).

The red pen

Common traps: mistake → fix

  • Mistake: Running handlers synchronously

    Fix: the order differs from real promises.

  • Mistake: No chaining

    Fix: then must return a new promise.

  • Mistake: No guard against double resolve.

  • Mistake: Not adopting thenables

    Fix: returning a promise from then would give the promise itself as the value.

Easy to hard

Questions interviewers ask, easy to hard

  1. Implement MyPromise with then and catch. (Flipkart Senior, Sept 2025)
  2. Support then after the promise has already resolved, and several thens.
  3. Make then chainable and handle a throw inside a handler.
  4. Adopt thenables returned from handlers.
  5. Add static all and a cancel() method.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview