What exactly is the difference between these two statements?
funcThatReturnsAPromise()
.then(() => { /* success */ })
.catch(() => { /* fail */ });
funcThatReturnsAPromise()
.then(() => { /* success */ }, () => { /* fail */ });
In summary: then : when a promise is successful, you can then use the resolved data. catch : when a promise fails, you catch the error, and do something with the error information. finally : when a promise settles (fails or passes), you can finally do something.
The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.
If you return a normal value or a promise that eventually resolves from the . catch() handler (thus "handling" the error), then the promise chain switches to the resolved state and the . then() handler after the . catch() will be called.
// the execution: catch -> catch new Promise((resolve, reject) => { throw new Error("Whoops!"); }). catch(function(error) { // (*) if (error instanceof URIError) { // handle it } else { alert("Can't handle such error"); throw error; // throwing this or another error jumps to the next catch } }).
Besides .catch(fn)
being a shortcut for .then(null, fn)
, the difference in your examples is that
funcThatReturnsAPromise()
.then(() => { /* success */ })
.catch(() => { /* fail */ });
// is equivalent to
const p1 = funcThatReturnsAPromise()
const p2 = p1.then(() => { /* success */ })
const p3 = p2.catch(() => { /*
executed if p1 is rejected
executed if p2 is rejected
*/ })
While the second one is
funcThatReturnsAPromise()
.then(() => { /* success */ }, () => { /* fail */ });
// equivalent to
const p1 = funcThatReturnsAPromise()
const p2 = p1.then(
() => { /* success */ },
() => { /*
executed if p1 is rejected
(p2 will be actually resolved by the result of this function only when p1 is rejected)
*/ }
);
.catch(foo)
is equal to .then(undefined, foo)
But there is a difference between your code samples:
funcThatReturnsAPromise()
.then(() => { /* success case of funcThatReturnsAPromise */ })
.catch(() => { /* both fail case of funcThatReturnsAPromise
and fail case of "then" function */ });
funcThatReturnsAPromise()
.then(() => { /* success case of funcThatReturnsAPromise */ },
() => { /* fail case of funcThatReturnsAPromise */ });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With