JavaScript Promise reject() Method Tutorial

In this section, we will learn what the Promise reject() method is and how to use it in JavaScript.

Note: we’re assuming you’re already familiar with the Promise object.

What is Promise reject() Method in JavaScript?

A promise does not necessarily need to begin in a pending state and utilize an executor function to reach a settled state. It is possible to instantiate a promise in the `rejected` state by invoking the `Promise.reject()` static method.

Note: The `reject()` method instantiates a rejected promise and throws an asynchronous error (which will not be caught by the try/catch and can only be catched by a rejection handler)

Promise reject() Method Syntax:

Promise.reject(value);

Promise reject() Method Parameters

The method takes one argument and that is the reason for rejection. This argument could be as simple as a string value to an object of type Promise.

Promise reject() Method return value

The return value of this method is a Promise that is in rejection state.

Example: using Promise reject() method in JavaScript

const prom = Promise.reject("The promise is rejected");

prom.then(value=>{
  console.log("The resolved handler");
  console.log(value);
},failed=>{
  console.log("The rejection of the 'then' method");
  console.log(failed);
}).finally(()=>{
  console.log("The finally handler");
});

Output:

The rejection of the 'then' method

The promise is rejected

The finally handler

As you can see, the `onRejected()` handler of the promise `prom` is called. This is because we’ve created a promise via the `reject()` method, and that means the promise is already rejected.

Note: if we pass another promise object into the `reject()` method, it will use that promise as the reason of the rejection!

Example: using a Promise object as the argument of reject() method

const pr = new Promise((resolve, reject)=>{
  resolve("The promise resolved");
});
const prom = Promise.reject(pr);

console.log(prom==pr);

prom.then(value=>{
  console.log("The resolved handler");
  console.log(value);
},failed=>{
  console.log("The rejection of the 'then' method");
  console.log(failed);
}).finally(()=>{
  console.log("The finally handler");
});

Output:

false

The rejection of the 'then' method

Promise {<fulfilled>: "The promise resolved"}

The finally handler

The result of the statement below is false:

console.log(prom==pr);

This proves that if we pass another promise to the `reject()` method, it will simply use that promise as the reason of rejection.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies