将 json 个对象传递给另一个函数以在 for 循环中调用

Pass json objects into another function to call in a for loop

我有一个函数可以通过 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 始终 return 未定义

尝试使用:

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);
    };
  }
}