I need to wait until all the "unit" has been loaded, but my code doesn't give me the result I expected. Maybe I'm wrong with the logic behind Deferred objects, how can I manage all the call one-by-one? My code is:
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) );
};
};
:==== UPDATE ====:
I try another way but my units array is still empty the "console.dir" is called at runtime before any ajax request:
this.display = function() {
loadCalls();
$.when.apply( $, calls ).then( console.dir(units) );
};