In my current code I'm filling the Object arr with ajax calls. After the calls, I would like to sort them. My code to fill the arr is working fine but the sequence of the code is not what I want to.
In Debug mode I see he first try to sort the empty Arr and afterwards the ajax call is running.
Is there a way to say first run the whole Ajax script and after filling run the sort part?
Code:
//Sortering
var arr = {};
var key = "";
var teller = 0;
for (var i = 0; i < schedule_id.length; i++) {
//Ajax call maken
$.ajax({
url: "http://api.viewer.zmags.com/schedules/" + schedule_id[i] + "?key=" + api_key
})
.done(function(data) {
//Check publicatieID is not null
if (undefined === data.scheduleEntries[default_pub] || null === data.scheduleEntries[default_pub]) {} else {
var key = schedule_id[teller];
//loopen doorheen resultaat call
$.each(data.scheduleEntries, function(index, entry) {
arr[key] = entry.startDate;
})
}
teller++;
})
}
//////////////////////////////////////////////////////////////////////////
//I want this part after the arr is filled
var timeArray = [],
newObj = {};
for (var key in arr) {
timeArray.push([key, arr[key]]);
}
timeArray.sort(function(a, b) {
return new Date(a[1]) - new Date(b[1])
});
//console.log(timeArray);
var j = 0,
k = 1;
for (var i = 0; i < timeArray.length; i++) {
newObj[timeArray[i][j]] = new Date(timeArray[i][k]);
}