call(back)

Implement a Promise

Write a Promise from scratch. Get the core right first — settling once, asynchronous callbacks, chaining — then add catch, finally and the static helpers.

new MyPromise((resolve, reject) => { ... })
p.then(onFulfilled, onRejected)   // returns a new MyPromise; chains
p.catch(onRejected)
p.finally(onFinally)
MyPromise.resolve(v) / MyPromise.reject(r) / MyPromise.all(iterable)

Rules the grader checks

  • A promise settles once: later resolve/reject calls are ignored; an executor that throws rejects.
  • Callbacks run asynchronously — schedule them with queueMicrotask, never synchronously and never with setTimeout. The grader stubs both to observe ordering: microtasks must run before timers.
  • then returns a new promise whose fate is the callback's return value; a returned promise or thenable is adopted, not passed through; a throwing callback rejects.
  • Missing handlers pass the value or reason through.
  • all keeps input order and rejects on the first rejection.

Hints

Hint 1

State machine: pending → fulfilled | rejected, one way. Guard resolve/reject with a called flag so only the first call wins, and wrap the executor in try/catch.

Hint 2

Keep a queue of {onFulfilled, onRejected, resolve, reject} handlers. then pushes one and returns the new promise those resolve/reject belong to; settling drains the queue, each in queueMicrotask.

Hint 3

Resolution procedure: if the value has a callable then, call it and adopt whatever it settles with (recursively) — that's what makes return anotherPromise inside a callback work.

Asked at