Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reject a promise from inside then function

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); ?

like image 621
chinabuffet Avatar asked Jan 21 '14 14:01

chinabuffet


People also ask

How do you reject in a Promise?

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.

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.

How do you resolve and reject a Promise?

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.

How do you return from Promise then?

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.


1 Answers

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     }); 
like image 56
Bergi Avatar answered Oct 06 '22 00:10

Bergi