This post explains the usage and working of the JavaScript promise.reject() method.
How to Use the Promise.reject() Method in JavaScript?
The promise object is specifically used for asynchronous calls which are resolved or rejected. For this purpose, the catch() method is utilized to capture and hold the rejected message and forward it to the user console. The method returns the promise object that contains the rejected message, specifying the reason.
The syntax of the JavaScript Promise.reject() method is provided below:
Syntax
reason: The reason for rejecting the promise.
Example 1
An example is considered using the reject method, the following example code is executed.
Code
console.log("An example of use promise reject() method");
const prom = newPromise((resolve, reject) => {
setTimeout(() => {
reject('The promise return fail');
}, 3000);
});
// use catch() method
prom.catch(er => {
console.log(er);
});
The description of the above code is provided here:
- A message is displayed “An example of use promise reject() method” using the console.log() method.
- After that, the Promise object is created with a new keyword.
- Another method, the setTimeout() is utilized in which a reject method is called that displays the message after 3000 milliseconds.
Output
The outcome shows that the message “The promise return fail” is displayed using the reject() method in JavaScript. Moreover, it is displayed after 3 seconds by utilizing the setTimeout() method.
Example 2
An example is considered using the promise reject() method by utilizing the if and else statements in JavaScript.
Code
returnnewPromise((resolve, reject) => {
console.log("Welcome to JavaScript");
console.log("Welcome to Linuxhint");
if (Math.random() >.5) {
resolve("SUCCESS")
} else {
reject("FAILURE")
}
})
}
const promise = met1();
In this code:
- A user-defined met1() method is created that returns the output of the Promise object.
- After that, two parameters, resolve and reject are passed to this method.
- In this method, two messages are displayed using the console.log() method.
- After that, check the condition, if the Math.random() method returns a value greater than.5, then the resolve() method is called. Otherwise, the reject() method is executed.
- At the end of the code, an object promise is initialized to call the met1() method.
Output
The output returns the executable code by displaying the messages in the console window.
Conclusion
The Promise.reject() method is employed to display the reason for the error, either specified by the backend or front-end. The method is utilized for asynchronous operations. In this article, an overview is demonstrated by providing the syntax. Moreover, an example is adapted to better understand the concept of the Promise.reject() method in JavaScript. The method is specifically used for debugging purposes.