我需要等到所有"单位"已加载,但我的代码没有给我我预期的结果。也许我对Deferred对象背后的逻辑错了,我怎样才能逐个管理所有的调用呢? 我的代码是:
function A(selectors) {
var section = $(selectors);
var dimension=12;
var calls = [];
var units = [];
function getAjaxCall(date) {
return $.ajax({
url: "myurl",
data: {
"date": date
},
type: "GET",
dataType: "json"
}).done(
function(r) {
buildUnit(r.tot);
}
);
};
function loadCalls() {
var today = new Timer();
for(var i=0; i<dimension; i++) {
calls.push(
getAjaxCall(today.getFullDate())
);
//sposto la data un giorno prima
var tDate = today.getObj();
var newDate = tDate.getDate()-1;
tDate.setDate(newDate);
}
};
function buildUnit(count) {
var unit = new Unit();
unit.setCount(count);
units.push(unit);
};
this.display = function() {
$.when( loadCalls() )
//this is call before every ajax-call and is empty
.done( console.dir(units) );
};
};
:====更新====:
我尝试了另一种方法,但我的单位数组仍然是空的&#34; console.dir&#34;在任何ajax请求之前在运行时调用:
this.display = function() {
loadCalls();
$.when.apply( $, calls ).then( console.dir(units) );
};