In this pattern, we first handle any errors using the catch
method and then resolve or reject the promise based on whether an error occurred. We can also use the try-catch
block to catch errors and handle them in a more structured way.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
// Simulate network error
throw new Error("Network error");
}, 2000);
});
}
fetchData().then(data => console.log(data))
.catch(error => {
console.error("An error occurred:", error);
// Resolve the promise with an empty value or reject it
resolve();
});
In this pattern, we first handle any resolved values using the then
method and then catch any errors using the catch
method.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
// Simulate network error
throw new Error("Network error");
}, 2000);
});
}
fetchData().then(data => console.log(data))
.catch(error => {
console.error("An error occurred:", error);
});
In this pattern, we use a combination of both the Catch-First and Catch-Last patterns to handle errors and resolved values in a more robust manner.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
// Simulate network error
throw new Error("Network error");
}, 2000);
});
}
fetchData().then(data => console.log(data))
.catch(error => {
console.error("An error occurred:", error);
// Resolve the promise with an empty value or reject it
resolve();
})
.finally(() => {
console.log("Promise completed");
});
In summary, there are several error handling patterns that can be used for error handling with promises. The choice of pattern depends on the specific requirements and use case of the application.