Home
← All questions

Polyfill of Promise in JavaScript

HardPremiumJavaScript

Asked at Microsoft

JavaScript interview practice: Implement a Promise from scratch with then/catch and state machine.

Problem

Writing a polyfill of Promise in JavaScript is a common senior frontend interview task that tests async state, chaining and the event loop.

Implement a MyPromise class whose constructor takes an executor (resolve, reject), with .then(onFulfilled, onRejected) and .catch(onRejected) methods.

Requirements

  • A promise starts as pending and settles exactly once, to either fulfilled with a value or rejected with a reason. Later resolve/reject calls are ignored.
  • The executor runs synchronously inside the constructor. If it throws, the promise is rejected with the thrown error.
  • .then can be called any number of times, before or after settling; handlers run once each, in registration order.
  • Handlers always run asynchronously, after the current synchronous code, even if the promise is already settled.
  • .then returns a new MyPromise, so calls can be chained. The value returned by a handler fulfills the next promise; a thrown error rejects it.
  • If a handler for the current outcome is missing, the value or reason passes through to the next promise in the chain.
  • .catch(onRejected) behaves like .then with only a rejection handler.

Example

new MyPromise((resolve) => setTimeout(() => resolve(2), 10))
  .then((v) => v * 10)
  .then((v) => { throw new Error("bad " + v); })
  .catch((e) => e.message)
  .then(console.log); // "bad 20"

const p = new MyPromise((resolve) => resolve("now"));
p.then(console.log);
console.log("sync");
// sync
// now

Follow-ups

  • How would you adopt a promise (or thenable) returned from a handler?
  • How would you add finally?
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium