在JavaScript中,我如何/应该使用XMLHttpRequest的async / await? [英] In JavaScript how do I/should I use async/await with XMLHttpRequest?
问题描述
完全披露:我有资格拥有中级JavaScript知识。所以这略高于我此时的经验水平。
Full disclosure: I'd qualify myself as having intermediate JavaScript knowledge. So this is slightly above my experience level at this time.
我有一个Google Chrome扩展程序,它为本地文件执行AJAX请求:///
一旦页面加载。在我从请求中得到响应之后,我将在代码中使用多个函数中返回的代码。大部分时间我都会在需要运行的代码之前收到响应。但有时我不会,一切都会中断。
I've got a Google Chrome Extension that does an AJAX request for a local file:///
as soon as a page loads. After I get the response back from the request I use the returned code in several functions later on in my code. Most of the time I get the response back before my code that needs it runs. But sometimes I don't and everything breaks.
现在,我假设我可以将所有相关代码抛出 xhr.onload
下面。但这似乎效率低下?我有许多依赖于响应的移动部件,将它们全部放在那里似乎很糟糕。
Now, I assume I could just throw all of the relevant code inside of the xhr.onload
below. But that seems really inefficient? I have a lot of moving parts that rely on the response and it seems bad to put them all in there.
我已经阅读了几篇与async / await相关的文章我在理解这个概念时遇到了麻烦。我也不是100%肯定我正在以正确的方式看待这个问题。我是否应该考虑使用async / await?
I've perused several articles related to async/await and I'm having trouble grasping the concept. I'm also not 100% positive I'm looking at this the right way. Should I even be considering using async/await?
以下是我的AJAX请求的代码。
Here is the code for my AJAX request.
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();
假设我后来在我的代码中有一堆需要触发的函数。现在它们看起来像:
Let's say I've got a bunch of functions that need to fire afterwards later on in my code. Right now they just look like:
function doTheThing(code) {
// I hope the response is ready.
}
最好的方法是什么?仅供参考,获取
API不是一个选项。
What's the best way to approach this? FYI, the Fetch
API isn't an option.
以下是我的代码结构的高级视图。
Here's a high level view of how my code is structured.
// 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 / await就像这样:
I usually do async/await like this:
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(...);
});
此处有明确的xhr函数:
Promisified xhr function here:
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中,我如何/应该使用XMLHttpRequest的async / await?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!