To handleerrors in a Promise in JavaScript, you can use the .catch() method or the second argument of the
.then() method. Both approaches allow you to specify a callback function that will be executed when the Promise is rejected (i.e., in the rejected state).
Here's how to handle errors using both methods:
Using .catch() method:
const myPromise = new Promise((resolve, reject) => {
// Simulate a failed asynchronous operation
setTimeout(() => {
reject("Operation failed!"); // Reject the promise with an error
}, 2000);
});
myPromise
.then((result) => {
// This function will not be called on rejection
console.log("Success:", result);
})
.catch((error) => {
// This function will be called when the Promise is rejected
console.error("Error:", error);
});
In this example, if myPromise is rejected (after a 2-second delay), the
.catch() method's callback function is called, allowing you to handle the error.
Using the second argument of .then():
const myPromise = new Promise((resolve, reject) => {
// Simulate a failed asynchronous operation
setTimeout(() => {
reject("Operation failed!"); // Reject the promise with an error
}, 2000);
});
myPromise
.then((result) => {
// This function will not be called on rejection
console.log("Success:", result);
})
.catch((error) => {
// This function will be called when the Promise is rejected
console.error("Error:", error);
});
You can use either approach to handle errors in a Promise. The key is to provide a rejection callback function that will be invoked when the Promise is rejected. Inside this callback, you can perform error handling tasks, such as logging the error, displaying an error message, or taking appropriate action based on the error.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To handle errors in a Promise in JavaScript, you can use the .catch() method or the second argument of the .then() method. Both approaches allow you to specify a callback function that will be executed when the Promise is rejected (i.e., in the rejected state).
Here's how to handle errors using both methods:
Using .catch() method:
In this example, if myPromise is rejected (after a 2-second delay), the .catch() method's callback function is called, allowing you to handle the error.
Using the second argument of .then():
You can use either approach to handle errors in a Promise. The key is to provide a rejection callback function that will be invoked when the Promise is rejected. Inside this callback, you can perform error handling tasks, such as logging the error, displaying an error message, or taking appropriate action based on the error.