Build MyPromise from scratch
The deep-end interview question: implement a minimal, spec-inspired Promise class yourself. MyPromise should support:
new MyPromise(executor)whereexecutor(resolve, reject)runs synchronously..then(onFulfilled, onRejected)returning a newMyPromise, so chains work..catch(onRejected)as sugar for.then(undefined, onRejected).- Once settled, the state is locked in (calling
resolve/rejectagain does nothing). - A
.thenregistered after the promise has already settled still fires (with its result delivered asynchronously, a microtask, not a synchronous call). - Because your
.then(onFulfilled, onRejected)has the same shape the language expects, realawaitwill actually work on aMyPromise, you don't need to do anything special for that part.
You do not need to handle a callback returning another thenable/promise (no recursive resolution), keep it to plain values.
const p = new MyPromise((resolve) => resolve(42));
await p; // 42
p.then((v) => v * 2).then((v) => console.log(v)); // 84