chinabuffet
chinabuffet

Reputation: 5578

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

Upvotes: 110

Views: 61752

Answers (2)

shamaseen
shamaseen

Reputation: 2478

Use Promise.reject

Like this

function test()
{
    return new Promise((resolve, reject) => {
        resolve(null)
    }).then(() => console.info('yes')).then(() => {
        return Promise.reject('hek');
    })
}

test().then(() => console.info('resolved')).catch(() => console.info('rejected'))

Upvotes: 1

Bergi
Bergi

Reputation: 664185

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

Upvotes: 109

Related Questions