Javascript 如何在异步xhr请求中返回值?

Javascript 如何在异步xhr请求中返回值?,javascript,asynchronous,xmlhttprequest,Javascript,Asynchronous,Xmlhttprequest,如何将loadFile.responseText作为loadFile.Open设置为true(异步)的xhr()函数中的返回值返回。。。当我将请求设置为同步(false)时,返回值。我确实理解为什么会发生这种情况,但我想知道是否有一种方法可以通过异步设置来实现这一点 loadFile.open("GET", url, true); // no response 整体功能: function xhr(url, async){ var data = ''; var loadFi

如何将
loadFile.responseText
作为loadFile.Open设置为true(异步)的xhr()函数中的返回值返回。。。当我将请求设置为同步(false)时,返回值。我确实理解为什么会发生这种情况,但我想知道是否有一种方法可以通过异步设置来实现这一点

loadFile.open("GET", url, true); // no response
整体功能:

function xhr(url, async){

    var data = '';

    var loadFile = new XMLHttpRequest();

        loadFile.overrideMimeType("application/json");

        loadFile.open("GET", url, false); // when true, no value is returned (of course)

        loadFile.onreadystatechange = function() {

            if (loadFile.readyState === 4 && loadFile.status == "200")
            {
                data = JSON.parse( loadFile.responseText );

                return data;
            }
        }

        loadFile.send(null);

    return loadFile.onreadystatechange();
}
我一直在寻找答案,发现了这个,它不是一个重复


如果需要的话,我不介意完全改变方向。你能提供一个实际的基本示例或一个可靠的建议来帮助我实现这一目标吗?

我将回答这个问题,然后将其作为副本关闭。这个答案纯粹是对你的具体问题的澄清。真正的答案是阅读和理解副本

在这里,我将复制并粘贴重复答案中的相关部分:

变成

 foo(function(result) {
     // Code that depends on 'result'
 });
因此,您的代码应重组为:

function xhr(url, callback){

    var data = '';

    var loadFile = new XMLHttpRequest();

        loadFile.overrideMimeType("application/json");

        loadFile.open("GET", url, false); // when true, no value is returned (of course)

        loadFile.onreadystatechange = function() {

            if (loadFile.readyState === 4 && loadFile.status == "200")
            {
                data = JSON.parse( loadFile.responseText );

                callback(data); //// NOTE: this is how you return the value
            }
        }

        loadFile.send(null);

    loadFile.onreadystatechange();
}
以及如何使用返回的结果:

xhr(some_url, function (result) {
    // use result here

    // NO, it's not possible to get result outside this function
    // If you really want you can pass it further to other functions:

    do_something_with(result);

    // but you can NEVER return it
});
基本上,您需要重新构造代码并习惯回调


有一些更奇特的方法可以执行回调,比如Promissions和更新版本的js async/await(返回Promissions),但它们都是回调。

如果您已经找到了答案(您尝试执行的操作是不可能的),那么您不了解什么?你试过使用回电或承诺吗?请向我们展示您的尝试或提出更具体的问题,否则我们只能重复规范。在另一个线程中提出的问题不同。我特别想问的是如何着手这样做。建议?回调或承诺的示例?我不想纠正现有函数中的错误。你对另一条线索有什么建议或评论吗?如何着手做什么?从异步函数返回值?你不能那样做。建议:使用回调或承诺代替。示例:太多了。@Bergi:答案只是从dup粘贴的副本。我希望将来对这个的搜索会重定向到dup。我不认为有什么新的补充。这是一个非常具体的澄清OP如何具体修改他的code@GRowing同样相关的是这个答案,它可能比我标记为副本的答案更清楚,也可能不清楚:我感谢@Bergi的澄清。非常感谢。您是否建议对XHR请求进行结构良好的阅读?
xhr(some_url, function (result) {
    // use result here

    // NO, it's not possible to get result outside this function
    // If you really want you can pass it further to other functions:

    do_something_with(result);

    // but you can NEVER return it
});