Returning data from anonymous, asynchronous functions? [duplicate]

混江龙づ霸主 提交于 2019-12-10 11:55:30

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/4353070/returning-data-from-anonymous-asynchronous-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!