Throwing an Error in jQuery's Deferred object

后端 未结 1 1675
情书的邮戳
情书的邮戳 2020-11-27 06:53

I have an $.ajax promise and want to check whether my (syntactically valid) response contains an error, triggering the rejected status in that case.

I have worked wi

相关标签:
1条回答
  • 2020-11-27 07:07

    Now updated for jQuery 1.8+

    The easiest way to tackle this is to run the response of $.ajax through .then to filter based on success or failure of the data.

    $.ajax()
        .then(function (response) {
            return $.Deferred(function (deferred) {
                var problem = hasError(response);
    
                if (problem) {
                    return deferred.reject(problem)
                }
    
                deferred.resolve(response);
            }).promise();
        });
    

    You could then return this new promise to whatever calling code would consume this:

    var request = function () {
        return $.ajax()
            .then(function (response) {
                return $.Deferred(function (deferred) {
                    var problem = hasError(response);
    
                    if (problem) {
                        return deferred.reject(problem)
                    }
    
                    deferred.resolve(response);
                }).promise();
            });
    };
    
    request()
        .done(function (response) {
            // handle success
        })
        .fail(function (problem) {
            // handle failure
        });
    
    0 讨论(0)
提交回复
热议问题