我已经编写了这段代码,以便从多个网址中获取内容。我想知道所有$.get
调用何时满足:
foo : function(arrIds){
var arrJqxhr = [];
var arrReturnedData = []
for ( var i = 0, l = arrIds.length; i < l; i++ ) {
var url = '/thing/' + arrIds[i].toString()
arrJqxhr[i] = $.get(url)
.done(function(data, textStatus, jqXHR) {
arrReturnedData.push(data);
})
}
除了保持被调用.done
多少次之外还有更好的方法吗?
答案 0 :(得分:1)
您可以使用$.when
var arrReturnedData = [];
var arrJqxhr = $.map(arrIds, function (id) {
var url = '/thing/' + id.toString()
return $.get(url)
.done(function (data, textStatus, jqXHR) {
arrReturnedData.push(data);
})
});
$.when.apply($, arrJqxhr).then(function(){
//this will be called once all requests are successfully completed
$.each(arguments, function(i, arr){
arrReturnedData.push(arr[0])
});
});