完成/完成后如何在$ .each json数组上使用.promise().done()?

pao*_*com 17 each jquery promise

我想在$ .each完成后执行一些操作.

$.each(someArray, function(index, val) {

    //---------some async ajax action here per loop ---------
    $.ajax({...}).done(function(data){...});

}.promise().done(function(){...}); //<-------error here can't use with $.each
Run Code Online (Sandbox Code Playgroud)
  • 不是每个jQuery函数都有一个promise()
  • 我如何知道$ .each数组何时完成?
  • 我可以将someArray更改为$ someArray来使用它吗?

jfr*_*d00 37

你已经想通了,$.each()没有,.promise()所以你不能按照你想要的方式去做.相反,您可以使用它$.when()来跟踪一组Ajax函数返回的一堆promise是否已经解决:

var promises = [];
$.each(someArray, function(index, val) {
    //---------some async ajax action here per loop ---------
    promises.push($.ajax({...}).then(function(data){...}));
});
$.when.apply($, promises).then(function() {
    // code here when all ajax calls are done
    // you could also process all the results here if you want
    // rather than processing them individually
});
Run Code Online (Sandbox Code Playgroud)

或者,而不是你的$.each(),使用它有点清洁.map():

$.when.apply($, someArray.map(function(item) {
    return $.ajax({...}).then(function(data){...});
})).then(function() {
    // all ajax calls done now
});
Run Code Online (Sandbox Code Playgroud)