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.
then(function(resource) { return modifyResource(resource) }) . then(function(modifiedResource) { if (! isValid(modifiedResource)) { var validationError = getValidationError(modifiedResource); // fail promise with validationError } }) . catch(function() { // oh noes });
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.
reject() The Promise. reject() method returns a Promise object that is rejected with a given reason.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With