如何從異步調用返回響應? - 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
相關文章
相關標籤/搜索