Promise.reject
JS Functions
Easy
5 min
promises
async
polyfills
Implement promiseReject(reason), which behaves like Promise.reject. It returns a new promise that is already rejected with reason.
promiseReject(new Error('nope')).catch((e) => e.message); // 'nope'
const p = Promise.resolve('fine');
promiseReject(p).catch((reason) => reason === p); // true: the promise itself is the reason
const thenable = { then: (resolve) => resolve('ignored') };
promiseReject(thenable).catch((reason) => reason === thenable); // true
Requirements
- Do not call the native
Promise.reject. You may usenew Promise. - Always return a new promise, even if
reasonis itself a promise. reasonis used exactly as given. Promises and thenables are not unwrapped or adopted, and theirthenmethod is never called.- Any value is allowed as a reason, including
undefined.
Follow-up
- Why is the asymmetry between
Promise.resolve(adopts) andPromise.reject(doesn't) intentional? - Why should you reject with
Errorobjects rather than strings?
Spotted a mistake or a rights concern? Report an issue