【发布时间】:2021-01-08 04:22:33
【问题描述】:
我有一个通过 XmlHTTPRequest 获取 json 对象列表的函数:
function getDataByXHR(method, url) {
let xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onload = function () {
console.log(xhr.response);
gameSettings = JSON.parse(xhr.response);
console.log(gameSettings);
this.data = gameSettings;
};
xhr.onerror = function () {
console.error("An error occur getting the XMLHttpRequest");
};
xhr.send();
}
如何将它们传递给这样的函数
function waitConsoleLog() {
const sleep = (ms) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
let count = 0;
console.log(this.data);
for (let index = 0; index < this.data.length; index++) {
async (element) => {
count++;
await sleep(500 * count);
console.log(element);
};
}
}
在 for 循环中使用,因为 data/gameSettings 总是返回未定义
【问题讨论】:
-
尝试将 JSON 分配给全局变量。
标签: javascript json async-await xmlhttprequest jsonparser