本文介绍了完成/完成后如何在$ .each json数组上使用.promise().done()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$.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 来使用它吗?
- Not every jQuery function has a
promise()
? - How do I know when $.each array is done?
- Can I change someArray to $someArray to use it?
推荐答案
如您所知,$.each()
没有.promise()
,因此您无法按照尝试的方式进行操作.相反,您可以使用$.when()
跟踪由一组Ajax函数返回的一堆承诺何时全部得到解决:
As you've figured out, $.each()
doesn't have a .promise()
so you can't do it the way you were trying to. Instead, you can use $.when()
to track when a bunch of promises returned by a group of Ajax functions have all been resolved:
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()
更加干净:
Or, rather than your $.each()
, it's a bit cleaner to use .map()
:
$.when.apply($, someArray.map(function(item) {
return $.ajax({...}).then(function(data){...});
})).then(function() {
// all ajax calls done now
});
这篇关于完成/完成后如何在$ .each json数组上使用.promise().done()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!