FrontendPro

101Implement a Promise library with .then(), .catch(), chaining, and asynchronous handler scheduling

hardAbout 60 minutesCodingpromisesevent-looppolyfillspromises-a-plus

Problem

Implement class MyPromise that follows the Promises/A+ rules, without using the built-in Promise anywhere in your implementation:

  • new MyPromise((resolve, reject) => …): the executor runs synchronously; if it throws, the promise rejects. A promise settles once; later calls are ignored.
  • then(onFulfilled, onRejected) returns a new promise. Handlers run asynchronously (in a microtask, use queueMicrotask), in the order they were registered, even if the promise is already settled.
  • A handler's return value resolves the next promise; a thrown error rejects it. Missing handlers pass values and errors through.
  • Resolution procedure: resolving with a thenable (any object or function with a then method) adopts its state; resolving a promise with itself rejects with a TypeError; a thenable's callbacks are honoured only once.
  • catch(onRejected), finally(onFinally) (runs on both outcomes, passes the original value or error through unless it throws), and static MyPromise.resolve and MyPromise.reject.
new MyPromise((resolve) => setTimeout(() => resolve(2), 10))
  .then((n) => n * 10)
  .then((n) => { throw new Error(`too big: ${n}`); })
  .catch((e) => e.message)
  .finally(() => console.log("done"))
  .then(console.log); // "too big: 20"

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Video walkthroughs

Stuck? Watch someone solve it, then try again on your own.

JavaScript Polyfills - Writing a polyfill for JavaScript Promise Part - 1 | Code along with VishalCode along with Vishal on YouTubeOpen on YouTube
Jake Archibald on the web browser event loop, setTimeout, micro tasks, requestAnimationFrame, ...JSConf on YouTubeOpen on YouTube

Step-by-step

Keep state ("pending", "fulfilled", "rejected"), value, and a list of handlers waiting for the result. settle(state, value) changes the state only if it is still pending, then flushes the handlers.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 5 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever