2

I have understood that Promise is a special object in which javascript which helps us to deal with asynchronous tasks and catch errors which arise from it .

I am familiar with the below usage :

func_returning_promise( )
.then((param)=>{do stuff with the param ; }
.catch((error) =>{console.log(error); }

How ever I quite didn't like the .then and .catch used like this and so I stored the Promise in a variable var myprom = func_returning_promise() .

But when I call the "then" and "catch" methods like this , the error doesn't get handled at all and doesn't execute the catch handler.

var myprom = func_returning_promise();
myprom.then((param)=> do stuff with param ) ; 
myprom.catch((error)=> console.log(error)) ;

Why I am still getting errored out and why itsn't the catch handler executing ?

Has it got anything to do with the semicolon ; put at the end of then method ?

This is not a duplicate of question Placement of catch before or after then

My question isn't about the placement of then and catch at all which the mentioned question addresses.

Natesh bhat
  • 12,274
  • 10
  • 84
  • 125
  • Try tagging the catch onto the the end of the then and see if that helps. `myprom.then((param)=> do stuff with param ).catch...` – Faz Dec 25 '17 at 10:16
  • 1
    Possible duplicate of [Placement of catch BEFORE and AFTER then](https://stackoverflow.com/questions/42013104/placement-of-catch-before-and-after-then) – Ricky Ruiz Dec 25 '17 at 10:19

2 Answers2

10

Your first and second code snippets are not equivalent.

In the first one, the .catch() would handle any error thrown in func_returning_promise() or in the .then() handler.

In the second one, .catch() is chained off of the original promise, so it would only catch errors thrown in func_returning_promise().

To achieve the equivalent of the first example without chaining, you would have to assign the result of .then to a variable and call catch on that:

var myprom = func_returning_promise();

var mysecondprom = myprom.then((param)=> do stuff with param ) ; 

mysecondprom.catch((error)=> console.log(error)) ;

Promises were designed to be chained. So why not chain them?

JLRishe
  • 99,490
  • 19
  • 131
  • 169
2

In your first code, you are catching the errors that occur in func_returning_promise OR the errors that occur inside the then callback. In your second code, you only catch the errors in myprom, ignoring the ones thrown in the then chain. You may do:

 var myprom = func_returning_promise();
 myprom
  .then((param) => /*do stuff with param*/)
  .catch((error)=> console.log(error))
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151