Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 834
shinzou Avatar asked Apr 09 '17 12:04

shinzou


People also ask

How do you reject a Promise then function?

then(function(resource) { return modifyResource(resource) }) . then(function(modifiedResource) { if (! isValid(modifiedResource)) { var validationError = getValidationError(modifiedResource); // fail promise with validationError } }) . catch(function() { // oh noes });

How do you reject a Promise chain?

In order to reject the promise chain from a . catch() you need to do something similar as a normal catch and fail at the error recovery by inducing another error. You can throw or return a rejected promise to that effect.

Does rejecting a Promise return?

reject() The Promise. reject() method returns a Promise object that is rejected with a given reason.

What happens when you reject a Promise JavaScript?

If it rejects, it is rejected with the reason from the first promise that was rejected. Returns a new Promise object that is rejected with the given reason. Returns a new Promise object that is resolved with the given value.


Video Answer


1 Answers

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.

like image 192
Estus Flask Avatar answered Sep 23 '22 01:09

Estus Flask