Promise.reject() – What Is the JavaScript Promise reject() Method?
Promise.reject() is a static method of the Promise
constructor function. It returns a new promise object that is rejected based on the reason you’ve passed as its argument.
Syntax of the Promise.reject()
Static Method
Promise.reject(reason);
The Promise.reject()
syntax is a simpler alternative to new Promise(...)
—especially when you do not need to use the Promise
constructor’s callback argument.
For instance, here’s one way to reject a promise object to the "Oops😲!"
string value:
const myPromise = new Promise(function (resolve, reject) { reject("Oops😲!");});
console.log(myPromise);
// The invocation above will return:Promise { <state>: "rejected", <reason>: "Oops😲!" }
You can alternatively use the Promise.reject()
method to simplify your code like so:
const myPromise = Promise.reject("Oops😲!");
console.log(myPromise);
// The invocation above will return:Promise { <state>: "rejected", <reason>: "Oops😲!" }
Important Stuff to Know about Promise.reject()
Here are two essential facts to remember while using the Promise.reject()
static method.
Promise.reject()
’s argument determines the rejected reason
A promise object’s rejected reason depends on the data type you passed as an argument to the reject()
method.
For instance, the promise object below is rejected based on the reason of an array because we passed in an array data type as an argument to the reject()
method.
const myPromise = Promise.reject(["Oops😲!"]);
console.log(myPromise);
// The invocation above will return:Promise { <state>: "rejected", <reason>: Array [ "Oops😲!" ] }
Promise.reject()
does not unwrap its argument
Unlike the resolve()
method, Promise.reject()
will not unwrap its argument down to its non-thenable value.
Therefore, suppose you pass in a thenable value as an argument to the reject()
method. In that case, Promise.reject()
will use the thenable value as the reason for the rejected state—without unwrapping it.
Here’s an example:
const myPromise = Promise.reject({ then: function () { return "Oops😲!"; },});
console.log(myPromise);
// The invocation above will return:Promise { <state>: "rejected", <reason>: Object { then: then() } }
When the snippet above passed a thenable object as an argument to the Promise.reject()
method, it did not unwrap the thenable object down to its non-thenable value. Therefore, the resultant promise object resolved to the rejected reason of the thenable object.