Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

javascript - 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

question from:https://stackoverflow.com/questions/65623424/pass-json-objects-into-another-function-to-call-in-a-for-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...