问题描述
我有一个通过 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 总是返回为 undefined
解决方法
尝试使用:
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;
waitConsoleLog(this.data)
};
xhr.onerror = function () {
console.error("An error occur getting the XMLHttpRequest");
};
xhr.send();
}
function waitConsoleLog(data) {
const sleep = (ms) => {
return new Promise((resolve) => setTimeout(resolve,ms));
};
let count = 0;
console.log(data);
for (let index = 0; index < data.length; index++) {
async (element) => {
count++;
await sleep(500 * count);
console.log(element);
};
}
}