-1

Considering given code

function foo() {
    var bar = [];
    asyncRequest.get(function(data) {
        bar = data;
    });

    return bar;
}

how do you return bar when it's filled with data from callback and not before? In 50% cases return is reached earlier then callback finishes and empty array is returned.

MelkorNemesis
  • 3,415
  • 2
  • 20
  • 20
  • 3
    You can't. That's why the function accepts a callback in the first place. – Quentin Nov 12 '13 at 11:27
  • Simple: You don’t. You _can not_ use return in that place while executing asynchronous tasks. Whatever you want to do with the value the async request gets – do it from within the callback function. – CBroe Nov 12 '13 at 11:27
  • Yet another duplicate of [How to return AJAX response Text?](http://stackoverflow.com/questions/1225667/how-to-return-ajax-response-text) – Quentin Nov 12 '13 at 11:27

1 Answers1

2

how do you return bar when it's filled with data from callback and not before?

You can't. Instead, have the function accept a callback it calls with the result:

function foo(callback) {
    asyncRequest.get(function(data) {
        // (More stuff here, presumably)
        callback(data);
    });
}

Or if it's really just a pass-through (there's nothing where I've written "(More stuff here, presumably)"), then:

function foo(callback) {
    asyncRequest.get(callback);
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875