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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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
Also can I make var myCombinedArray = fetchData(function (myCombinedArray) {}); . If not how do I get the data into my variable.
@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...
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.