91
votes

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

1
throw validationErrorkavun
>< I had a feeling it would be something silly/easy that. Guess I kept thinking that I had to call a dedicated rejection function or return a failed Promise instead. So from inside a promise/thenable, any returned value that is not a new Promise will be considered the resolved value? And if I throw an error, that's the same as returning an immediately rejected Promise? If you post that as an answer I'll accept it.chinabuffet
You are probably looking for the accepted answer here stackoverflow.com/questions/17800176/…crad

1 Answers

98
votes

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