This is probably a silly question, but mid promise chain, how do you reject a promise from inside one of the then functions? For example:
someActionThatReturnsAPromise() .then(function(resource) { return modifyResource(resource) }) .then(function(modifiedResource) { if (!isValid(modifiedResource)) { var validationError = getValidationError(modifiedResource); // fail promise with validationError } }) .catch(function() { // oh noes });
There's no longer a reference to the original resolve/reject function or the PromiseResolver. Am I just supposed to add return Promise.reject(validationError);
?
reject() method is used to return a rejected Promise object with a given reason for rejection. It is used for debugging purposes and selective error catching.
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.
A Promise executor should call only one resolve or one reject . Once one state is changed (pending => fulfilled or pending => rejected), that's all. Any further calls to resolve or reject will be ignored.
Return valuereturns a value, the promise returned by then gets resolved with the returned value as its value. doesn't return anything, the promise returned by then gets resolved with an undefined value. throws an error, the promise returned by then gets rejected with the thrown error as its value.
Am I just supposed to add
return Promise.reject(validationError);
?
Yes. However, it's that complicated only in jQuery, with a Promise/A+-compliant library you also could simply
throw validationError;
So your code would then look like
someActionThatReturnsAPromise() .then(modifyResource) .then(function(modifiedResource) { if (!isValid(modifiedResource)) throw getValidationError(modifiedResource); // else ! return modifiedResource; }) .catch(function() { // oh noes });
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