【发布时间】:2018-08-04 18:53:52
【问题描述】:
完全披露:我认为自己具有中级 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();
假设我有一堆函数需要稍后在我的代码中触发。现在它们看起来像:
function doTheThing(code) {
// I hope the response is ready.
}
解决这个问题的最佳方法是什么?仅供参考,Fetch API 不是一个选项。
这是我的代码结构的高级视图。
// AJAX request begins.
// ...
// A whole bunch of synchronous code that isn't dependant on
// the results of my AJAX request. (eg. Creating and appending
// some new DOM nodes, calculating some variables) I don't want
// to wait for the AJAX response when I could be building this stuff instead.
// ...
// Some synchronous code that is dependant on both my AJAX
// request and the previous synchronous code being complete.
// ...
// Some more synchronous code that needs the above line to
// be complete.
【问题讨论】:
-
您是否考虑过改用Fetch?它从一开始就是基于 Promise 的。
-
将代码放入回调中绝对不会影响效率或性能。它只是代码,回调只是回调。代码要么执行,要么不执行。
-
要将 XMLHttpRequest 与 async/await 一起使用,您需要做出承诺
-
只需从
onload函数内部调用doTheThing(code)。 -
@E.Sundin Fetch 不适用于我需要的本地
file:///文件。 @JaromandaX 这就是我的想法。但是很难让它发挥作用。
标签: javascript async-await xmlhttprequest