开发者

Returning data from anonymous, asynchronous functions? [duplicate]

This question already has answers here: How do I return the response from an asynchronous call? (41 answers) Closed 9 years ago.

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜