How to use JavaScript Promise catch()
There are a few ways to take advantage of the Promise catch method. The catch() method is run when the Promise is rejected or throws an error. Return value from a Promise is passed forward to the catch() method. Promises can be chained as well. It simply forwards the return value from the chained Promise to the catch method if the Promise is rejected or an error is thrown.
A basic example of using catch() with a Promise reject:
// using Promise.reject
let rejectPromise = new Promise(function(resolve, reject){
reject("promise rejected")
})
function displayCatch(x) {
console.log(x)
}
rejectPromise.catch(x => displayCatch(x))
A basic example of using catch() by throwing an error from the promise:
// throw an error
let promiseError = new Promise(function(resolve, reject){
throw "throw error"
})
function displayCatch(x) {
console.log(x)
}
promiseError.catch(x => displayCatch(x));
Chained promises. Reject or throw error from chained Promise:
let resolvePromise = new Promise(function(resolve, reject) {
setTimeout(resolve, 50, "resolved chained");
})
function resolveDisplay(x) {
console.log(x)
throw "throw error from chained Promise"
}
function displayCatch(x) {
console.log(x)
}
resolvePromise.then(x => resolveDisplay(x)).catch(x => displayCatch(x))