1

I have setup my JavaScript thus

function getData(uri) {
    var $result;
    var demoAPI = uri;
    $.getJSON(demoAPI, function(data) {
        $.each(data, function(key, val) {
            names[key] = val["name"];
            numbers.push(val["number"]);
        });
    }).done(function() {
            for(i = 0; i < names.length; i++) {
                var tmp = new Array(names[i], numbers[i]);
                result.push(tmp);
            }
            return result;
        });
}

Problem is, with this setup is I cannot use the function thus:

var values = getData('/users');

as the return statement is in a closure within the $.getJSON block, if I do call the return after said block it returns an empty array because it gets called before the ajax call is completed. I will encounter the same challenge if I attempt to use $.ajax(). I need help returning the generated array from my function getData().

IROEGBU
  • 948
  • 16
  • 33
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Karl-André Gagnon Apr 22 '14 at 12:44

1 Answers1

4

As you've discovered, you cannot reliably return data from asynchronous functions. You need to pass a callback function to be executed when the data is received. Try this:

function getData(uri, callbackFn) {
    var $result;
    $.getJSON(demoAPI, function(data) {
        $.each(data, function(key, val) {
            names[key] = val["name"];
            numbers.push(val["number"]);
        });
    }).done(function() {
            for(i = 0; i < names.length; i++) {
                var tmp = new Array(names[i], numbers[i]);
                result.push(tmp);
            }
            callbackFn(result);
        });
}

getData('/users', function(result) {
    // do what is required with the returned data...
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339