JavaScript Promise reject() Method

JavaScript promise.reject() method is used to create a new Promise object that is rejected with a specified reason. This method typically signals that a promise cannot fulfill its intended purpose, such as when a network request fails or the desired value cannot be found.

A promise has two possible outcomes: it will either be kept when the time comes or won’t. This is also the same for promises in JavaScript. So when we define a promise in JavaScript, it will be resolved when the time comes, or it will get rejected.

Syntax

Promise.reject(reason);

Parameters

The parameter reason is why this Promise was rejected.

Example

const p1 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
  setTimeout(() => {
    reject('fail promise');
  }, 1000);
});

p1.catch(error => { 
  console.log(error);
});

Output

Javascript Promise Reject Example | Promise.reject() Tutorial

In the above code example, we created a new Promise p1 that will be rejected with the message ‘fail promise’ after a delay of 1 second. Then, the catch method is called on p1 to handle the rejection.

When the reject function is called, the Promise’s state changes from “pending” to “rejected” and the value passed to reject becomes the rejection reason. In this case, the rejection reason is the string ‘fail promise’.

The catch method is a shorthand for attaching a rejection handler to a Promise. It takes a single argument, a function that will be called with the rejection reason when the Promise is rejected.

In this case, the function logs the rejection reason to the console.

Example 2

We can also debug the error if we throw an instanceof an Error object. For example, take a look at the following code.

const p1 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
  setTimeout(() => {
    reject(new Error('Promise failed'));
  }, 1000);
});

p1.then(error => { 
  console.log(error);
});

Output

Promise.reject() Tutorial

In the above code example, we created a new Promise p1 that will be rejected with an Error object with the message ‘Promise failed’ after a delay of 1 second. Then, the then method is called on p1 to handle the resolution of the Promise.

However, since the Promise is rejected, the then method’s callback will not be called. Instead, to handle the rejection, you would need to use the catch method or provide a second argument to the then method, a function that will be called with the rejection reason when the Promise is rejected.

That’s it for this tutorial.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.