Skip to content
Onsite

Implement Promise from Scratch

HardP2Coding

Implement a class MyPromise that behaves like a native Promise, without using Promise inside it. You may use queueMicrotask for scheduling.

  • new MyPromise(executor): calls executor(resolve, reject) immediately. If the executor throws, the promise rejects with the error (unless it has already settled). A promise settles only once; later calls to resolve or reject are ignored.
  • then(onFulfilled, onRejected) returns a new MyPromise. The handlers are always called asynchronously (in a microtask), even if the promise is already settled, in the order they were added. The returned promise resolves with the handler's return value, or rejects if the handler throws. If a handler is not a function, the value or reason passes through to the returned promise.
  • Resolving with a thenable (an object with a then method, including another MyPromise) makes the promise follow it. Resolving a promise with itself rejects with a TypeError.
  • catch(onRejected) is then(undefined, onRejected).
  • finally(callback) runs callback with no arguments after either outcome, then passes the original value or reason through. If callback throws or returns a rejected thenable, that error replaces the outcome; a returned thenable is waited for.
  • MyPromise.resolve(value) and MyPromise.reject(reason) create settled promises (resolve returns a MyPromise argument unchanged).

Instances must work with await, so they need a standard then.

Example 1

Input
new MyPromise(r => setTimeout(() => r(1), 10)) .then(v => v + 1) .then(v => log(v));
Output
logs 2 about 10 ms later

Constraints

  • Follow the Promises/A+ behavior for then and thenables.
  • Chains up to 10^3 long.

Hints

Run checks the 3 visible tests, Submit all 22.