Implement Promise.reject without unwrapping the reason
A data-fetching layer has functions that sometimes know up front that a request will fail, for example when a required ID is missing. They still return a promise so callers can handle every failure in one .catch. Promise.reject(reason) does exactly that, and you are going to build it yourself.
Implement rejectWith(reason). It returns a promise that is already rejected with reason.
rejectWith(reason) // => Promise rejected with reason
Promise (result instanceof Promise is true), and a new one on every call.reason itself, whatever it is: an Error, a string, null, undefined (also when called with no argument), or an object.reason is a promise, or any object with a then method, the rejection reason is that same object, and its then method is never called..catch handler attached right after the call has not run yet when the current code continues.Promise.reject.const error = new Error('Missing user id');
rejectWith(error).catch((reason) => {
reason === error; // => true
});
rejectWith('timeout').then(
() => 'never runs',
(reason) => reason, // => 'timeout'
);
const pending = Promise.resolve(5);
rejectWith(pending).catch((reason) => {
reason === pending; // => true (not 5)
});
rejectWith() instanceof Promise; // => true (rejected with undefined)