40Implement Promise.resolve() and Promise.reject()
mediumAbout 35 minutesCodingpromisesthenablespolyfills
Problem
Implement promiseResolve(value) and promiseReject(reason) without using Promise.resolve or Promise.reject.
promiseResolve(value):
- returns
valueitself when it is already a native promise; - adopts a thenable (any object or function with a
thenmethod): the returned promise settles however the thenable does; - otherwise returns a promise fulfilled with
value.
promiseReject(reason) returns a promise rejected with reason, never unwrapping it, even if reason is itself a promise.
const p = fetch("/api");
promiseResolve(p) === p; // true
const legacyThenable = { then(onOk) { onOk("data"); } };
await promiseResolve(legacyThenable); // "data"Requirements
- Call a thenable's
thenasynchronously (in a microtask), as the built-in does. - If reading
value.thenthrows, reject with that error. - If the thenable calls its callbacks more than once, only the first call counts.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Step-by-step
If value instanceof Promise and its constructor is Promise, return it. This saves an extra promise and an extra microtask, and it is why Promise.resolve(p) === p.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.