Search code examples
javascriptecmascript-6promisees6-promise

Reject a promise from then()


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.


Solution

  • 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.