0

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);
    }); 
}
Richie
  • 4,989
  • 24
  • 90
  • 177

1 Answers1

2

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

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Thanks for your comment. I had a very good read of the link and your post. Why I try to implement the callback I get "Callback is not a function". Can you help me a little bit more. I'm about to modify my post to show updated attempt – Richie Feb 20 '15 at 02:43
  • Also can I make var myCombinedArray = fetchData(function (myCombinedArray) {}); . If not how do I get the data into my variable. – Richie Feb 20 '15 at 02:47
  • 1
    @Richie you can't assign it to a variable like that as when `fetchData` is returned the data from the server is not yet loaded... – Arun P Johny Feb 20 '15 at 03:10
  • thanks your example helped me figure out what was wrong with my code. And then it all worked for me. This has been a good lesson for me on how to master callbacks – Richie Feb 20 '15 at 04:54