如何从异步调用返回响应? - How do I return the response from an asynchronous call?

问题:

I have a function foo which makes an Ajax request. 我有一个函数foo ,它发出Ajax请求。 How can I return the response from foo ? 如何返回foo的响应? ajax

I tried returning the value from the success callback as well as assigning the response to a local variable inside the function and returning that one, but none of those ways actually return the response. 我尝试从success回调中返回值,以及将响应分配给函数内部的局部变量并返回该局部变量,但这些方法均未真正返回响应。 异步

function foo() {
    var result;

    $.ajax({
        url: '...',
        success: function(response) {
            result = response;
            // return response; // <- I tried that one as well
        }
    });

    return result;
}

var result = foo(); // It always ends up being `undefined`.

解决方案:

参考一: https://stackoom.com/question/xfM1/如何从异步调用返回响应
参考二: https://oldbug.net/q/xfM1/How-do-I-return-the-response-from-an-asynchronous-call
相关文章
相关标签/搜索