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

我想在$ .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 
  • 不是每个jQuery函数都有promise()吗?
  • 我怎么知道$ .each数组什么时候完成?
  • 我可以将someArray更改为$ someArray来使用它吗?

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

 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 }); 

或者,而不是你的$.each() ,使用.map()有点干净:

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