全面披露:我认为自己具有中级 JavaScript 知识。所以这略高于我目前的经验水平。
我有一个 Google Chrome 扩展程序,一旦页面加载,它就会对本地 file:///
发出 AJAX 请求。当我从请求中得到响应后,我会在代码中的多个函数中使用返回的代码。大多数时候,我会在需要它的代码运行之前收到响应。但有时我不这样做,一切都会崩溃。
现在,我假设我可以将所有相关代码放入下面的 xhr.onload
中。但这似乎效率很低?我有很多依赖于响应的事件部件,将它们全部放在那里似乎很糟糕。
我仔细阅读了几篇与 async/await 相关的文章,但我很难理解这个概念。我也不是百分百肯定我看待这个问题的方式是正确的。我是否应该考虑使用 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 不是一个选项。
这是我的代码结构的高级 View 。
// 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.
最佳答案
我通常像这样进行异步/等待:
async function doAjaxThings() {
// await code here
let result = await makeRequest("GET", url);
// code below here will only execute when await makeRequest() finished loading
console.log(result);
}
document.addEventListener("DOMContentLoaded", function () {
doAjaxThings();
// create and manipulate your DOM here. doAjaxThings() will run asynchronously and not block your DOM rendering
document.createElement("...");
document.getElementById("...").addEventListener(...);
});
function makeRequest(method, url) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
关于javascript - 在 JavaScript 中,我/应该如何将 async/await 与 XMLHttpRequest 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48969495/