确保在jQuery中完成所有异步调用

时间:2013-04-18 10:00:29

标签: javascript jquery

我有一个使用jQuery进行大量异步API调用的webapp:s $ .get和$ .post方法。 在激活按钮(display:none / block)之前,我需要确保所有这些都已成功完成(HTTP状态代码200)。

有没有办法确保在jQuery中没有未完成的异常调用等待开箱即用?或者我是否需要自己跟踪?

我正在使用jQuery v1.8.3。

2 个答案:

答案 0 :(得分:5)

您可以创建“Master Deferred”,只有在所有其他Deferred(AJAX请求)成功完成后才会解决;

jQuery.when(jQuery.get('/foo'), jQuery.post('/bar'), jQuery.get('/baz')).done(function () {
    $('button').show();
});

语法是将每个Deferred作为参数传递给jQuery.when(),后者返回Deferred,当一个失败或完成所有这些操作后,它会解析。

如果你事先不知道你有多少AJAX请求,已经将它们放在一个数组中,或者只是不想使用上面的那些,你可以像这样使用Function.apply;

var ajaxRequests = [jQuery.get('/foo'), jQuery.post('/bar'), jQuery.get('/baz')];

jQuery.when.apply(jQuery, ajaxRequests).done(function () {
    $('button').show();
});

有关详细信息,请参阅http://api.jquery.com/jQuery.whenhttp://www.mattlunn.me.uk/blog/2014/01/tracking-joining-parallel-ajax-requests-with-jquery/ (我的博客)

答案 1 :(得分:1)

this post开始,您应该可以使用相同的代码(不需要abortAll功能,因此它已被删除,并且已添加对活动请求的检查):

$.xhrPool = [];
$.ajaxSetup({
    beforeSend: function(jqXHR) {
        $.xhrPool.push(jqXHR);
    },
    complete: function(jqXHR) {
        var index = $.xhrPool.indexOf(jqXHR);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
        if ($.xhrPool.length > 0) {
            //There are still active requests - keep the button hidden
        } else {
            //There's no more active requests - show the button
        }
    }
});

这适用于通过jQuery请求的所有ajax请求,包括$.get$.post$.ajax