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): callsexecutor(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 toresolveorrejectare ignored.then(onFulfilled, onRejected)returns a newMyPromise. 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
thenmethod, including anotherMyPromise) makes the promise follow it. Resolving a promise with itself rejects with aTypeError. catch(onRejected)isthen(undefined, onRejected).finally(callback)runscallbackwith no arguments after either outcome, then passes the original value or reason through. Ifcallbackthrows or returns a rejected thenable, that error replaces the outcome; a returned thenable is waited for.MyPromise.resolve(value)andMyPromise.reject(reason)create settled promises (resolvereturns aMyPromiseargument 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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 22. ⌘Enter runs, ⌘⇧Enter submits.