I have a couple of functions that use a jQuery AJAX call to retrieve an XML file from my server, and convert it into something usable. Look at the following code:
getBalanceXML: function (callback) {
$.ajax({
type: 'GET',
url: 'Content/saldotracking.xml',
dataType: 'xml',
success: callback,
error: function () { throw new Exception("getBalanceXML(): Failed to load XML file"); }
})
},
getBalanceBarChart: function (xml) {
var balanceArray = [];
$(xml).find('Balance').each(function () {
var nodeObject = {
//fill a JavaScript object with values from the XML file in the format I need
}
balanceArray.push(nodeObject);
});
console.log(balanceArray);
return balanceArray;
}
Now, when I call this function with:
var stuff = getBalanceXML(getBalanceBarChart);
alert(typeof(stuff));
The stuff var is still undefined. Following the other answers on StackOverflow, I pass the getBalanceChart function as a parameter to the getBalanceXML function, which does the AJAX call. Success! Now getBalanceChart can also use the XML file gained from the AJAX call. However, all I've done is move the synchronization problem to another function. There still comes a point where a synchronous part of my program needs the array that comes from an asynchronous function.
What do I do?