You can do it...
...just use catch
and return something from it, then use then
on the promise .catch
returns:
thePromise
.catch(err => err)
.then(resultOrError => {
// Your code
});
The argument your then
callback receives (resultOrError
in the above) will be the resolved value if the promise was resolved, or the rejected value (loosely, "error") if it was rejected. You can naturally do something more in catch
if you want to differentiate them.
Example (run it a few times, you'll see it get resolved, and also rejected):
let p = new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.5) {
resolve("success");
} else {
reject("error");
}
}, 0);
});
p.catch(err => err).then(resultOrError => {
console.log("Got this:", resultOrError);
});
...but alternately
...you can just have a a common function both callbacks call, after using the resolved value or the rejected value:
function doSomethingNoMatterWhat() {
// ...
}
thePromise
.then(result => {
// Presumably use `result`, then:
doSomethingNoMatterWhat();
})
.catch(error => {
// Presumably use `error`, then:
doSomethingNoMatterWhat();
});