I have a javascript function which waits for multiple ajax calls and then combines the responses into a single javascript array. I then need to return the array (data) from the function but don't know how I can do it.
Can I have some help on this please.
var myCombinedArray = fetchData();
function fetchData() {
var data = [];
$.when(fetchThisYearsData(),fetchLastYearsData()).done(function(dataThisYear, dataLastYear){
data[0] = dataThisYear[0];
data[1] = dataLastYear[0];
console.log(data);
});
return data;
}
I have read enough to know that myCombinedArray will be empty because the ajax is asynchronous but I don't know what to do to achive my desired result.
thanks
Update
I've tried to implement the callback but am a bit lost. I am getting an error "callback is not a function".
$(function () {
var myCombinedArray;
fetchData(function (myCombinedArray) {
//what to do here?
});
console.log(myCombinedArray);
})
function fetchData(callback) {
$.when(fetchThisYearsData(), fetchLastYearsData()).done(function(dataThisYear, dataLastYear){
var data = [];
data.push(dataThisYear[0]);
data.push(dataLastYear[0]);
callback(data);
});
}