How to reject a promise from inside then function

JavascriptPromise

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchinabuffetView Question on Stackoverflow
Solution 1 - JavascriptBergiView Answer on Stackoverflow