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
// Initialize a promise variable and // use the reject() method with a // reason as a parameter let 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); }); |
Output:
I am a reason of error
Example 2:
JavaScript
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" ); }); |
Output:
rejected the promise, something wrong happened
Example 3:
JavaScript
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" ); }); |
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