In the promise, what's the difference between using catch and the second argument then?

What is the difference between these two statements?

funcThatReturnsAPromise() .then(() => { /* success */ }) .catch(() => { /* fail */ }); funcThatReturnsAPromise() .then(() => { /* success */ }, () => { /* fail */ }); 
+5
source share
3 answers

Besides .catch(fn) , which is 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 */ }) 

Bye second

 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) */ } ); 
+5
source

then (..) takes one or two parameters, the first for the callback to execute, and the second for the failure callback. If passed or otherwise passed as a non-functional value, the default callback is replaced accordingly. The default execution callback simply passes the message together, while the default rejection callback simply retells (propagates) the cause of the error it receives. catch (..) only accepts the reject callback as a parameter and automatically replaces the default execution callback as just discussed. In other words, its equivalent is then (null, ...):

 p . then ( fulfilled ); p . then ( fulfilled , rejected ); p . catch ( rejected ); // or `p.then( null, rejected )` 

then (..) and catch (..) also create and return a new promise that can be used to express Promise chain flow control. If the execution or rejection of the callback has an exception, the returned promise is rejected. If either the callback returns an immediate, not a promise, non-thenable value, this value is set as execution for the returned promise. If the execution handler specifically returns a promise or a subsequent value, this value is unpacked and the resolution of the promised promise becomes.

- From "Don't Know Jace", Kyle Simpson

+2
source

.catch(foo) equals .then(undefined, foo)

But there are differences 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 */ }); 
+2
source

Source: https://habr.com/ru/post/1258281/


All Articles