相关疑难解决方法(0)

如何从异步调用返回响应?

我有一个foo发出Ajax请求的函数.我怎样才能从中回复foo

我尝试从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`.
Run Code Online (Sandbox Code Playgroud)

javascript ajax jquery asynchronous xmlhttprequest

5208
推荐指数
38
解决办法
134万
查看次数

在JavaScript中,我如何/应该使用XMLHttpRequest的async/await?

完全披露:我有资格拥有中级JavaScript知识.所以这略高于我此时的经验水平.

我有一个Google Chrome扩展程序,只要file:///页面加载就会为本地执行AJAX请求.在我从请求中得到响应之后,我将在代码中使用多个函数中返回的代码.大部分时间我都会在需要运行的代码之前收到响应.但有时我不会,一切都会破裂.

现在,我假设我可以抛出下面的所有相关代码xhr.onload.但这似乎效率低下?我有许多依赖于响应的活动部件,将它们全部放在那里似乎很糟糕.

我已经阅读了几篇与async/await相关的文章,并且我在理解这个概念时遇到了麻烦.我也不是100%肯定我正在以正确的方式看待这个问题.我是否应该考虑使用async/await?

这是我的AJAX请求的代码.

  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.onload = function(e) {
    code = xhr.response;
  };
  xhr.onerror = function () {
    console.error("** An error occurred during the XMLHttpRequest");
  };
  xhr.send();
Run Code Online (Sandbox Code Playgroud)

假设我后来在我的代码中有一些需要触发的函数.现在他们看起来像:

function doTheThing(code) {
  // I hope the response is ready.
}
Run Code Online (Sandbox Code Playgroud)

什么是最好的方法来解决这个问题?仅供参考,FetchAPI不是一种选择.

这是我的代码结构的高级视图.

// AJAX request begins.

// ...

// A whole bunch of synchronous code that isn't dependant on 
// the results of my AJAX request. …
Run Code Online (Sandbox Code Playgroud)

javascript xmlhttprequest async-await

22
推荐指数
3
解决办法
2万
查看次数