Richie
Richie

Reputation: 5199

jquery when function to wait for multiple ajax calls

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);
    }); 
}

Upvotes: 0

Views: 163

Answers (1)

Arun P Johny
Arun P Johny

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

Related Questions