jQuery Deferred: Rejecting a Promise from within a Done Filter

前端 未结 1 405
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 04:39

Fyi, I\'m just starting to learn jQuery promises, so I may be a bit confused here.

Anyway, I have an AJAX request that I want to reject from within a done filter bas

1条回答
  •  时光说笑
    2020-12-15 04:53

    In jQuery (unlike some other libs), transmogrifying a promise from a 'resolved' state to an 'rejected' state is slightly verbose, requiring the explicit creation and rejection of a new Deferred.

    function foo() {
        return doAJAXRequest().then(function (data, textStatus, jqXHR) {
            if (data.responseText == "YES") {
                return doOtherAJAXRequest(data);
            } else {
                return $.Deferred().reject(jqXHR, data, 'Not YES').promise();
            }
        });
    )
    

    Here, the promise returned if data.responseText !== "YES" mimics (in part) a failed ajax request, while still allowing data to be passed. This is (probably) important for the downstream .fail() handler, which must handle both genuine ajax failures AND transmogrified success conditions, without knowing which one occurred until it reads errorThrown.

    foo().fail(function(jqXHR, textStatus, errorThrown) {
        if(errorThrown == 'Not YES') {
            //transmogrified success
            var data = textStatus;
            ...
        }
        else {
            //genuine ajax failure
            ...
        }
    }); 
    

    It is generally easier to pass data in this way rather than re-obtaining it from the jqXHR object. This is particularly true with JSON encoded data, which would otherwise need to be decoded a second time in the fail handler.

    0 讨论(0)
提交回复
热议问题