Reputation: 5199
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
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);
});
}
Upvotes: 0
Views: 163
Reputation: 388316
You can use a callback function which will be called once all the data is populated
fetchData(function (myCombinedArray) {
//do your stuff
});
function fetchData(callback) {
$.when(fetchThisYearsData(), fetchLastYearsData()).done(function (dataThisYear, dataLastYear) {
var data = [];
data.push(dataThisYear[0]);
data.push(dataLastYear[0]);
console.log(data);
callback(data);
});
}
Read More
Upvotes: 2