等到 each() 函数中的所有 ajax 查询都使用 $.when() 完成

Wait until all ajax queries in each() function are finished using $.when()

在检查 $.each() 函数中包含的 ajax 查询没有错误后,如何 运行 callback()?

var resp_error = false;
$(".items").each(function() {
    ajax_item($(this)).done(function(resp){
        if (resp.val == 0)    return (resp_error = true);
    });
});
if (!resp_error)    callback();

其中 ajax_item(item) 是延迟的 ajax 查询:

function ajax_item(item) {
    return $.ajax({
       ...
    });
};

val 由 ajax 查询返回并在 val = 0.

时触发错误 (resp_error)

我认为最好的方法是使用 $.when(),但我找不到编码方法?

最简单的方法是:

$(document).ajaxStop(function() {
  // place code to be executed on completion of last outstanding ajax call here
});

好的,我找到了!

var resp_error = false;
var ajax_calls = [];
$(".items").each(function() {
    ajax_calls.push(ajax_item($(this)).done(function(resp){
       if (resp.val == 0)    return (resp_error = true);
    }));
});
$.when.apply($, ajax_calls).then(function() {
    if (!resp_error)    callback();
});