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
pendingand settles exactly once, to eitherfulfilledwith a value orrejectedwith a reason. Laterresolve/rejectcalls are ignored. - The executor runs synchronously inside the constructor. If it throws, the promise is rejected with the thrown error.
.thencan 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.
.thenreturns a newMyPromise, 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.thenwith 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?