数组数据每隔第二个事件仅呈现到HTML表一次,否则未定义 [英] Array data only renders to HTML table every second event, otherwise undefined

查看:95
本文介绍了数组数据每隔第二个事件仅呈现到HTML表一次,否则未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// Relevant code: 

const searchBtn = document.getElementById("search-btn");
const input = document.getElementById("input");
const leftTable = document.querySelector("#left-table");
let url = "https://api.github.com/search/repositories?q=?";
let tagsUrl;
let dataArr;
let names = [];
let language = [];
let latestTag = [];
let tableDataArr = [names, language, latestTag];

// Fetch first 2 items for repos containing user query
function search(newURL) {
  fetch(newURL, {
    headers: {
      "Authorization": "xxxx" 
    }
  })
    .then(resp => {
      return resp.json();
    })
    .then(data => {
      dataArr = data.items.slice(0, 2);
      return extractData();
    });
  input.value = ""; 
}

// Extract necessary values from returned object (language, name, latest tag) and push to corresponding arrays
function extractData() {
  dataArr.forEach(i => {
    names.push(i.full_name);
    language.push(i.language);
    fetch(i.tags_url)
      .then(resp => {
        return resp.json();
      })
      .then(resp => {
        if (resp[0]) {
         latestTag.push(resp[0].name);
        } else {
         latestTag.push(" ");
        }
        return console.log(tableDataArr);
      });
    //  getLatestTag(i.tags_url);
  });
  renderData();
}

// Render array data to HTML table
function renderData() {
  tableDataArr[0].forEach((i, j) => {
    let newRow = document.createElement("tr");
    newRow.className = "row";
    newRow.innerHTML = `<td class='cell'>${i}</td>
    <td class='cell'>${tableDataArr[1][j]}</td>
    <td class='cell'>${tableDataArr[2][j]}</td>
    <td class='cell'><button class='add-btn'>Add</button></td>`;
    leftTable.appendChild(newRow);
  });
}

// User input event listeners
searchBtn.addEventListener("click", () => {
  search(url + input.value);
});

input.addEventListener("keyup", e => {
  if (e.keyCode === 13) {
    search(url + input.value);
  }
});

在事件侦听器触发后,我需要tableDataArr中每个数组的内容才能呈现为HTML表.每次呈现tableDataArr [0]和tableDataArr [1]中的内容都没有问题.

I need the contents from each array inside tableDataArr to render to a HTML table after an event listener fires. The contents from tableDataArr[0] and tableDataArr[1] are rendering every time with no issue.

但是,tableDataArr [2]中的内容在第一次调用时呈现未定义的状态,然后在下一次调用中呈现正确的状态,然后呈现未定义的状态,依此类推,在未定义和数据之间采用这种交替模式.这是怎么回事?

But, the contents from tableDataArr[2] render undefined with the first call, then render properly the next call, then undefined and so on with this alternating pattern between undefined and the data. What is going on here?

推荐答案

提取,然后链接的thens将返回Promise对象.您可以将所有这些内容推送到一个数组中,并使用Promise.all()在调用renderData()之前检查所有获取是否完整,然后

Fetch and the chained thens will return a Promise object. you can push all of this into an array and use Promise.all() to check if all your fetches and thens are complete before calling renderData()

此示例代码将指导您...

This sample code will guide you...

// Extract necessary values from returned object (language, name, latest tag) and push to corresponding arrays
function extractData() {
  let psArr = [];
  dataArr.forEach(i => {
    names.push(i.full_name);
    language.push(i.language);
    let ps = fetch(i.tags_url)
      .then(resp => {
        return resp.json();
      })
      .then(resp => {
        if (resp[0]) {
         latestTag.push(resp[0].name);
        } else {
         latestTag.push(" ");
        }
        return resp;
      });
    psArr.push(ps);
    //  getLatestTag(i.tags_url);
  });
  Promise.all(psArr).then(()=>{
    renderData();
    });
}

请务必注意,当将then链接到承诺时,分配给变量的承诺是最后链接的then的承诺.

It is important to note the when chaining thens to a promise, the promise that is assigned to the variable is the promise of the last chained then.

此外,由于这都是异步操作,因此顺序可能会根据获取的完成情况而改变,这可能导致无法预测的行为.

Also since this is all asynchronous the order can change depending on completion of the fetches, and this could result in unpredictable behavior.

这篇关于数组数据每隔第二个事件仅呈现到HTML表一次,否则未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆