Search code examples
javascriptjsonasync-awaitxmlhttprequestjsonparser

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


I have a function that gets a list of json objects through XmlHTTPRequest:

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

How can I pass them into a function like this

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

to use in the for loop since data/gameSettings always return as undefined


Solution

  • Try Using:

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