jQuery Deferred-等待多个AJAX请求完成 [英] jQuery Deferred - waiting for multiple AJAX requests to finish

查看:465
本文介绍了jQuery Deferred-等待多个AJAX请求完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3层深度的递延ajax调用链,理想情况下,当最深层结束时,它们将完全兑现承诺(这使我很感冒……我们需要更深入!" ).

I have a three layer deep chain of deferred ajax calls, and ideally they are going to kick the promise all the way up when the deepest layer finishes (makes me thing of Inception... "we need to go deeper!").

问题是我要一次发送许多ajax请求(可能是数百个),并且需要推迟直到所有请求都完成为止.我不能依靠最后完成的最后一个.

The problem is that I'm sending off many ajax requests (possibly hundreds) at once and need to defer until all of them are done. I can't rely on the last one being done last.

function updateAllNotes() {
    return $.Deferred(function(dfd_uan) {
        getcount = 0;
        getreturn = 0;
        for (i = 0; i <= index.data.length - 1; i++) {
            getcount++;
            $.when(getNote(index.data[i].key)).done(function() {
                // getNote is another deferred
                getreturn++
            });
        };
        // need help here
        // when getreturn == getcount, dfd_uan.resolve()
    }).promise();
};

推荐答案

您可以将.when().apply()与多个递延一起使用.极其有用:

You can use .when(), and .apply() with multiple deferred. Extremely useful:

function updateAllNotes() {
    var getarray = [],
        i, len;

    for (i = 0, len = data.length; i < len; i += 1) {
        getarray.push(getNote(data[i].key));
    };

    $.when.apply($, getarray).done(function() {
        // do things that need to wait until ALL gets are done
    });
}

这篇关于jQuery Deferred-等待多个AJAX请求完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆