$.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
promise()
?答案 0 :(得分:35)
正如您所知,$.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
});
:
{{1}}