Hacker News new | ask | show | jobs
by mariusc23 3359 days ago
Wouldn't using the second parameter of .then() to catch exceptions work instead of .catch()?

http://stackoverflow.com/a/33278420

2 comments

Yes, but if the success handler throws you won't catch it. For example:

  promise.then(function(){
    throw new Error('Oh no, not caught');
  }, function(err){

  });
But this will catch it:

  promise.then(function(){
    throw new Error('Oh no!');
  }).catch(function(err){
    // Caught it ;)
  });
As will this:

  promise.then(function(){
    throw new Error('Oh no!');
  }).then(null, function(err){
    // Caught it ;)
  });
Point being that your error handling need to be absolute last, and not paired with a success handler.
It doesn't matter. The problem is that `callback(null)` throws, and in the `Promise` land this will never result in an uncaught exception. An exception directly inside any `Promise` callback produces another `Promise` in the chain instead.

You could at best use `setTimeout` or `nextTick` to escape from `Promise`'s call stack and throw there.

Good point! I thought of solving the callback getting called twice problem and didn't think of the bigger picture that mocha needs to catch the assertion error. I like the setTimeout/nextTick trick (well, ideally use Promises and async/await instead).