Skip to content
Related Articles

Related Articles

Improve Article

JavaScript promise reject() Method

  • Last Updated : 08 Mar, 2021

A promise is an object which is responsible for making a promise in a callback function with 2 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.

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.



The examples below illustrate the reject() method:

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>

Output:

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :