Skip to content
Related Articles

Related Articles

JavaScript promise reject() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 31 May, 2022
View Discussion
Improve Article
Save Article

A promise is a JavaScript object which is responsible for handling callbacks and other asynchronous events or data with 2 different possible states, it either resolves or rejects.

The Promise.reject() method is used to return a rejected Promise object with a given reason for rejection. It is used for debugging purposes and selective error catching. The catch() method can be used for logging the output of the reject() method to the console that is catch() method acts as a career which carries the rejected message from Promise.reject() method and displays that in user’s console.

Syntax:

Promise.reject(reason)

Parameter: This method accepts a single parameter as mentioned above and described below:

  • reason: It is the reason for which the promise is rejected.

Return value: It returns the rejected promise with the given reason, either specified by user or via the backend.

The examples below illustrate the reject() method in very much simplified and accurate manner:

Example 1:

JavaScript




<script>
  // Initialize a promise variable and
  // use the reject() method with a
  // reason as a parameter
  var promise = Promise.reject("I am a reason of error");
 
  // Catch the promise and pass the
  // function for logging the error in console
  promise.catch(function (error) {
    console.log(error);
  });
</script>
 
// This code is contributed by Aman Singla

Output:

I am a reason of error

Example 2:

JavaScript




<script>
  function main() {
    return new Promise(function (resolve, reject) {
      setTimeout(() => {
        // This is the error which is handled
        // according to network requests
        const error = true;
        reject();
      }, 2000);
    });
  }
  main().catch(function () {
    // Only executed if rejects the promise
    console.log("rejected the promise, something wrong happened");
  });
</script>

Output:

rejected the promise, something wrong happened

Example 3: 

JavaScript




<script>
  function main() {
    return new Promise(function (resolve, reject) {
      num = 100;
      if (num > 50) {
        reject();
      }
    });
  }
  main().catch(function () {
    // Only executed if rejects the promise
    console.log("Not greater than 100");
  });
</script>

Output:

Not greater than 100

Supported Browsers:

  • Google Chrome 32 and above
  • Edge 12 and above
  • Firefox 29 and above
  • Opera 19 and above
  • Safari 8 and above
  • Internet Explorer not supported

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!