Promise.resolve
JS Functions
Medium
15 min
promises
async
polyfills
event-loop
Implement promiseResolve(value), which behaves like Promise.resolve.
await promiseResolve(42); // 42
const p = Promise.resolve('x');
promiseResolve(p) === p; // true (native promises are returned as-is)
const thenable = {
then(onFulfilled) {
onFulfilled('adopted');
},
};
await promiseResolve(thenable); // 'adopted'
Requirements
- Do not call the native
Promise.resolve. You may usenew Promise. - If
valueis a native promise whoseconstructoris exactlyPromise, return the same object. - Any other promise, for example an instance of a
Promisesubclass, is wrapped in a new native promise that follows it. - Thenables (any object or function with a callable
thenproperty) are adopted. The returned promise follows whatever the thenable does:- It fulfills or rejects when the thenable calls its first or second callback. Only the first call counts.
- If calling
thenthrows before either callback was called, the promise rejects with that error. - If reading the
thenproperty throws (a throwing getter), the promise rejects with that error. thenis called asynchronously, in a later microtask, not duringpromiseResolve.
- Any other value fulfills the returned promise.
Follow-up
- Why does
Promise.resolveadopt thenables at all, instead of only real promises? - How many microtask ticks does adopting a promise cost compared to
await-ing a plain value?
Spotted a mistake or a rights concern? Report an issue