【问题标题】:Pass json objects into another function to call in a for loop将 json 对象传递给另一个函数以在 for 循环中调用
【发布时间】: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


【解决方案1】:

尝试使用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    相关资源
    最近更新 更多