Mastering the Fundamentals of JavaScript: A Beginner's Guide to Web Development
Chapter 10: Error Handling with Promises
In this chapter, we will discuss how to handle errors in JavaScript promises.
Promises provide a way to handle errors in asynchronous operations using the `.catch()` method. When a promise is rejected, the `.catch()` method is called with the error as the parameter.
Here is an example of using the `.catch()` method:
```
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error("Something went wrong"));
}, 1000);
});
promise.then(function(result) {
console.log(result);
}).catch(function(error) {
console.log(error.message); // "Something went wrong"
});
```
In this example, we have created a promise that will reject with an error after a delay of 1000 milliseconds. We have attached a `.catch()` method to the promise, which will be called when the promise is rejected. The `error` parameter in the `.catch()` function will contain the rejected error.
Chaining Promises with Error Handling:
Promises can be chained together with error handling using the `.catch()` method. Each `.then()` method returns a new promise that can be used in the next `.then()` method, and the final `.catch()` method can be used to handle any errors that occur during the chain.
Here is an example of chaining promises with error handling:
```
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(1);
}, 1000);
});
promise.then(function(result) {
console.log(result); // 1
return result + 1;
}).then(function(result) {
console.log(result); // 2
throw new Error("Something went wrong");
}).then(function(result) {
console.log(result);
}).catch(function(error) {
console.log(error.message); // "Something went wrong"
});
```
In this example, we have created a promise that will resolve with the value 1 after a delay of 1000 milliseconds. We have then chained three `.then()` methods together, with the second `.then()` method throwing an error. The final `.catch()` method is used to handle the error and log the error message.
Conclusion:
JavaScript promises provide a powerful way to handle asynchronous code in a structured and readable way. By understanding how to handle errors with the `.catch()` method, we can create more efficient and reliable asynchronous operations in our web applications.
Comments
Post a Comment