11

How can you reject a promise from inside its then()?

For example:

Promise.all(promiseArr).then(()=>{
  if(cond){
    //reject
  }
}).catch(()=>{ /*do something*/ });

The only relevant question I found was this: How to reject a promise from inside then function but it's from 2014, so there must be a better way then to throw by now with support of ES6.

Community
  • 1
  • 1
shinzou
  • 5,850
  • 10
  • 60
  • 124

2 Answers2

11

ES6/ES2015 is still JavaScript and doesn't offer anything new regarding promise rejection. In fact, native promises are ES6.

It is either

promise
.then(() => {
  return Promise.reject(...);
})
.catch(...);

or

promise
.then(() => {
  throw ...;
})
.catch(...);

And throw is more idiomatic (and generally more performant) way to do this.

This may not be true for other promise implementations. E.g. in AngularJS throw and $q.reject() is not the same thing.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • "E.g. in AngularJS throw and $q.reject() is not the same thing.": can you elaborate on this or provide a link to a more detailed information? I can't find anything regarding those differences. – ClementParis016 Nov 03 '17 at 17:31
  • I'm not sure if this is described in AngularJS docs, but `throw` inside `catch` or `then` results in uncaught error, while `return $q.reject()` results in rejected promise. – Estus Flask Nov 03 '17 at 18:19
2

I have found out (after hours of scratching my head) that if a throw is within an async method such as setTimeout(() => throw new Error('description')) it will be treated as an Unhandled Exception and will NOT end up in your .catch() block (you'll only see it in the console window) - see this article where I found out about that difference between throw and Promise.reject.

Pete
  • 67
  • 5