Skip to the solution
HardDSA10 min read

Implement a minimal Promise/A+ (MyPromise) with then/catch

733 views

The problem

Problem, as an interviewer would state it: "Implement a MyPromise class with a constructor that takes an executor, then, catch, and static resolve and reject. It must handle chaining and thenables. Discuss edge cases, runtime, and alternatives."

Examples:

Code
MyPromise.resolve(1).then((v) => v + 1).then((v) => { throw new Error("boom " + v); })
  .catch((e) => e.message).then((v) => v + "!");                      // "boom 2!"
MyPromise.resolve({ then(resolve) { resolve("adopted"); } });          // a thenable is adopted: "adopted"

Clarifying questions expected:

  • Which specification should it follow (Promises/A+), and how asynchronous must the callbacks be?
  • Should it accept any thenable (an object with a then method), not just its own instances?
  • Which extras are wanted: finally, all, race, unhandled-rejection reporting?

Code / implementation expected: Yes — a real, working class, ideally run against the official Promises/A+ conformance suite.

  • promise
  • custom-promise
  • thenable

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: MyPromise matches the native Promise on chaining, thenables, once-only guards and finally, and differs only in microtask tick counts

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 146 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Find the Intersection of N Arrays (Not Just Two)

Continue