我想在 $.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()
没有 .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
});
或者,使用 .map()
比使用 $.each()
更简洁:
$.when.apply($, someArray.map(function(item) {
return $.ajax({...}).then(function(data){...});
})).then(function() {
// all ajax calls done now
});
关于jquery - 完成/完成后如何在 $.each json 数组上使用 .promise().done() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24484601/