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


Solution 1:

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