0

Consider:

function ajaxCall(url, callback) {
    $.ajax({
        type: "GET",
        url: url,
        success: function (data) { // <-- fail point: where does the returned data go, now?
            // do stuff with data
            if ( callback ) {
                var ret = callback();
                if ( ret !== undefined ) {
                    return ret;
                }
            }
        }
    });
}

function fooBar() {
    return ajaxCall('some/url', function () {
        // do stuff
        return some_value;
    }
}

Right, so basically, I want to preserve the asynchronousness of the request so the browser doesn't hang, but still return a value in the end... This is a simplified example, even though I could probably simplify it even more.

In fact, the only obstacle I see is the transition between $.ajax and its success: anonymous function.

Hmph.

Félix Saparelli
  • 8,424
  • 6
  • 52
  • 67

1 Answers1

3

You can't use the calls asynchronously like this, the callbacks run later after your calling function has long since returned. Instead, what you need to do is call the function that needs the data as part of the (or the entire) callback, for example:

function ajaxCall(url, callback) {
  $.ajax({
    type: "GET",
    url: url,
    success: callback
  });
}

function fooBar() {
    ajaxCall('some/url', function (data) {
        functionThatNeedsData(data);
    });
}

That's just an example to show what's going on, in practice it could just be:

function fooBar() {
  $.get('some/url', functionThatNeedsData);
}

This just calls your functionThatNeedsData which gets the data from the request as the first argument...so as soon as the server responds with data, you're passing it on where it needs to do and doing the rest of your work with that data.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155