JavaScript promise reject() Method
Last Updated :
15 Dec, 2023
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 that carries the rejected message from the Promise.reject() method and displays that in the 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 the user or via the backend.
Example 1: In this example, a Promise is instantly rejected with the reason “I am a reason of error.” The catch() method logs the error to the console, showcasing a concise error-handling mechanism using JavaScript Promises.
JavaScript
let promise = Promise.reject( "I am a reason of error" );
promise. catch ( function (error) {
console.log(error);
});
|
Output
I am a reason of error
Example 2: In this example, a Promise in the main function simulates an error using a timeout and explicitly rejects it. The catch() method handles the rejection, logging “rejected the promise, something wrong happened” if an error occurs. This showcases asynchronous error handling with Promises in JavaScript.
JavaScript
function main() {
return new Promise( function (resolve, reject) {
setTimeout(() => {
const error = true ;
reject();
}, 2000);
});
}
main(). catch ( function () {
console.log( "rejected the promise, something wrong happened" );
});
|
Output:
rejected the promise, something wrong happened
Example 3: In this example, the main function creates a Promise where the condition checks if num is greater than 50. If true, the Promise is rejected. The catch() method handles the rejection, logging “Not greater than 100” to the console. This demonstrates a concise asynchronous error check using Promises in JavaScript.
JavaScript
function main() {
return new Promise( function (resolve, reject) {
num = 100;
if (num > 50) {
reject();
}
});
}
main(). catch ( function () {
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...