javascript - 如何仅在从 xmlhttp 调用接收到数据时才运行函数?

标签 javascript

只有当我的 getData() 函数返回数组时,如何运行 init() 函数在我的 dom 上设置innerHTML?

我很确定我需要在这里有某种异步等待函数,但我正在学习闭包 同时,我不确定我该如何做到这一点。

代码想要这样的东西:

const uiController = (function () {
  let data;

  const getData = async () => {
    const xml = new XMLHttpRequest();

    xml.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        data = getArray(JSON.parse(this.responseText));
      }
    };

    xml.open("GET", "data.json", true);
    xml.send();


  };

  getData();


  // I only want init to run when getData() is finished and my data variable is updated with the fetched data. 

  // Something similar to react ComponentDidMount
  const init = () => {

  document.getElementById("article-grid").innerHTML = `<div>${data}</div>`

  }

谢谢:)

最佳答案

const uiController = (function () {
let data;
// Something similar to react ComponentDidMount
const init = () => {
  document.getElementById("article-grid").innerHTML = `<div>${data}</div>`
}
const getData = async () => {
  const xml = new XMLHttpRequest();

  xml.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      data = getArray(JSON.parse(this.responseText));
      init(); // call inside readyState === 4 
    }
  };

  xml.open("GET", "data.json", true);
  xml.send();
};

getData();

关于javascript - 如何仅在从 xmlhttp 调用接收到数据时才运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62115240/

相关文章:

javascript - 同一页面上的两个 JQuery Ajax 调用

javascript - 使用jquery连续显示单词

javascript - MomentJs:Meteor 中没有定义时刻?

javascript - 如果已定义,为什么 Promise.all() 会触发 Array.prototype.then?

javascript - Trustpilot cross-origin error with carousel integration

javascript - 如果我想保留来自外部的事件,但防止自定义事件冒泡,如何隐藏 DOM

javascript - 变量的 setter 可以调用它的 getter

javascript - 用于查找两个字符串的最长公共(public)子序列的内存表也可以用于查找差异索引吗?

javascript - 使用 JavaScript 和 TensorFlow 通过 PoseNet 进行多人跟踪的问题

javascript - selectorgadget 是如何工作的?