1

I've simplified the scenario in the code below because I don't have room here to explain my use case, but basically I'm throwing an error from the "catch" block of a promise. How can I get the error to get passed on from that catch block (in the example below I want the error to get reported from the outer "catch" block of the "try/catch" that I have wrapped my code with):

var p = new Promise(function(resolve, reject) {
  setTimeout(function() {
    reject();
  }, 1000);


});

try {
  p.then(function() {
    console.log('promise resolved');
  }).catch(function() {
    throw new Error('I want to get out of this catch block!');
  });
} catch (err) {
  console.log('I want to report the error from here' + err.message);
}
Louis
  • 146,715
  • 28
  • 274
  • 320
mags
  • 590
  • 1
  • 8
  • 25
  • 2
    `try..catch` is a synchronous statement, you cannot do that. You can however chain another `.catch()` – elclanrs Jun 21 '16 at 17:27
  • I've rolled back your last edits. You asked an intelligible question, got an answer which you accepted. The community does not see in a good light radical changes to the question once there are answers that actually solve the problem expressed in the question, and especially once there's an *accepted* answer. Also, the new question is a duplicate of [this one](http://stackoverflow.com/questions/26571328/how-do-i-properly-test-promises-with-mocha-and-chai). Just return the promise: Mocha will take the rejection as a failure. – Louis Jun 21 '16 at 18:59
  • my bad. I was thinking i still needed an answer but then I figured out the answer. – mags Jun 21 '16 at 19:56

1 Answers1

1

The catch handlers in a Promise are just as asynchronous as the promise itself, so you can't revert back to synchronous flow/exception control from them. The function you're passing into .catch may not be called until well after the try/catch surrounding it has exited.

ssube
  • 47,010
  • 7
  • 103
  • 140
  • Yes, you are right. My example is bad. I will edit my example. I'm doing testing with mocha.js and I want the error to be passed to the test block. The test is async. – mags Jun 21 '16 at 18:32
  • @mags in that case, you need to pass it to the `done` callback that mocha provides. I bet there's an example of that on SO already, which might help you. – ssube Jun 21 '16 at 18:33
  • Yes, I was actually trying to get it to return as "pending". I think I need to do done(new Pending()). I will try that. – mags Jun 21 '16 at 18:45