完全披露:我认为自己具有中级 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.
}
解决这个问题的最佳方法是什么?仅供参考,FetchAPI 不是一种选择。
这是我的代码结构的高级视图。
// 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.