Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rejecting A jQuery Promise In A $.ajax Success Method

This is probably a stupid bug, but here goes.

I need to reject a jQuery Promise inside the success function of a $.ajax() call. The returned value "success" is a boolean value.

    function doSomething() {

        var myPromise = $.ajax({

            method: "POST",
                url: "/url/to/use",
                data: {"value":$("#value").val()},
                success: function(data) {
                    if (data.success == false) {
                        ConfirmMessage.showErrorMessage(data.messages[0]);
                        return new $.Deferred().reject().promise();
                    } else {
                        // do other stuff
                    }
                }
            });

            return myPromise;

        }

The doSomething() is used later on in a then() chain:

doSomething().then(doSomethingElse).then(soOn).then(soForth);

So I need to be able to reject the promise and break the chain.

Help appreciated.

like image 969
Jason Avatar asked Apr 27 '16 12:04

Jason


1 Answers

You cannot do that from a success callback. There's no reason to use one anyway. Just use then:

function doSomething() {
    return $.ajax({
        method: "POST",
        url: "/url/to/use",
        data: {"value":$("#value").val()},
    }).then(function(data) {
        if (data.success == false) {
            ConfirmMessage.showErrorMessage(data.messages[0]);
            return new $.Deferred().reject().promise();
        } else {
            // do other stuff
        }
    });
}
like image 171
Bergi Avatar answered Nov 16 '22 22:11

Bergi