5

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.

Jason
  • 3,943
  • 12
  • 64
  • 104
  • 1
    You can't reject an ajax promise after it's been resolved. Perhaps you can return another promise object which is either marked as resolved or rejected within the ajax callback rather than returning the ajax promise itself. – apokryfos Apr 27 '16 at 12:19

1 Answers1

6

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
        }
    });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • That did it. Hopefully this will be the last JQ promise related question for awhile. Thank you. – Jason Apr 27 '16 at 12:34
  • What does that `.promise()` in the end? Is it optional? – Tobi G. Aug 21 '19 at 13:08
  • 1
    @TobiG. https://api.jquery.com/deferred.promise/ - yes, it works without that as well but I consider it cleaner not to return deferreds. These days, I'd recommend to [dodge the jQuery promise implemenation](https://stackoverflow.com/a/31327725/1048572) though, which allows you to just `throw` in the `then` callback. – Bergi Aug 21 '19 at 13:59