0

In the following code the Promise.reject doesn't work unless I specifically use return Promise.reject(...). Why is this?

Promise.resolve('Promise 1 Done')
.then(function(result) {
  console.log(result);
  return 'Promise 2 Done'
}).then(function(result) {
  let j;
  try {
    j = JSON.parse("invalid will throw");
    console.log(j);
  } catch(err) {
    Promise.reject('Could not parse JSON');
  }

  console.log(result);
}).catch(function(err) {
  console.log(err);
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375

1 Answers1

1

Promise.reject creates a value, it does not throw an exception that breaks from the function like throw does. If you don't return that value, it will be ignored and the control flow continues.

Given you are inside a promise callback, you could (and possibly should) instead use

throw new Error('Could not parse JSON');
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Or return the rejected promise with `return Promise.reject('Could not parse JSON');`. – jfriend00 Aug 24 '16 at 01:16
  • @jfriend00: the OP knows that already, so yes :-) But [don't forget to wrap the message in an `Error`](http://stackoverflow.com/q/26020578/1048572). – Bergi Aug 24 '16 at 01:35
  • 1
    And I didn't think your answer illustrated the two options available in this context which would be useful for other readers too. Just suggesting an improvement. OP may also be confused about the difference between calling reject in a promise constructor vs this situation. – jfriend00 Aug 24 '16 at 01:50