Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Promise, what's the difference between using catch and the 2nd argument of then? [duplicate]

What exactly is the difference between these two statements?

funcThatReturnsAPromise()
  .then(() => { /* success */ })
  .catch(() => { /* fail */ });


funcThatReturnsAPromise()
  .then(() => { /* success */ }, () => { /* fail */ });
like image 271
ffxsam Avatar asked Oct 16 '16 07:10

ffxsam


People also ask

What is then and catch in promise?

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.

Does catch return a promise?

The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.

Can I use then after catch?

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.

How do you throw a mistake in promise catch?

// 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 } }).


2 Answers

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)
  */ }
);
like image 114
Mauricio Poppe Avatar answered Oct 14 '22 03:10

Mauricio Poppe


.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 */ });
like image 36
ykaragol Avatar answered Oct 14 '22 04:10

ykaragol