iT邦幫忙

0

JS AJAX的問題

  • 分享至 

  • xImage

各位大大好!
目前練習串接twitch的api
使用兩個url分別為Get Streams跟Search Channels
目標是顯示前20個實況頻道,如圖
https://ithelp.ithome.com.tw/upload/images/20220512/20125940BAhy6ai6s9.jpg

先發送請求到Get Streams取得前20個實況頻道資料,
再用迴圈取得頻道的user_name作為參數發送請求到Search Channels取得該用戶資料,
最後資料都取得後再進行畫面輸出。

目前我是用同步的方式,先取得頻道資料再取得用戶資料,並用一個全域變數將資料存起來,再輸出畫面。
雖然目前可以達成我要的效果,但是載入的時間有點長,請問該如何改會更好!

我的程式碼如下:

let container = document.querySelector(".container");
let data;
function getStream() {
  let xhr = new XMLHttpRequest();
  xhr.open(
    "Get",
    "https://api.twitch.tv/helix/streams?language=zh&game_id=511224",
    false
  );
  xhr.onload = function () {
    data = JSON.parse(this.responseText).data;
  };
  xhr.send();
}
function getProfileImg(userName, index) {
  let xhr = new XMLHttpRequest();
  xhr.open(
    "Get",
    `https://api.twitch.tv/helix/search/channels?query=${userName}&first=1`,
    false
  );
  xhr.onload = function () {
    let response = JSON.parse(this.responseText).data;
    data[index].profile_img = response[0].thumbnail_url;
  };
  xhr.send();
}

function loadStream() {
  getStream();
  for (let i = 0; i < data.length; i++) {
    getProfileImg(data[i].user_name, i);
  }
  for (let i of data) {
    let channel = document.createElement("div");
    let thumbnail = i.thumbnail_url.replace("{width}x{height}", "800x450");
    channel.classList.add("channel");
    channel.setAttribute("title", i.title);
    channel.innerHTML = `
        <div class="preview">
          <img src="${thumbnail}" />
        </div>
        <div class="channel_info">
          <div class="avatar">
            <img src="${i.profile_img}" />
          </div>
          <div class="info_content">
            <div class="channel_title">${i.title}</div>
            <div class="channel_name">${i.user_name}</div>
          </div>
        </div>
      `;
    container.appendChild(channel);
  }
}
loadStream();
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
Zero皇
iT邦研究生 3 級 ‧ 2022-05-12 19:40:21

你可以參考使用 Promise 改寫 XMLHttpRequest這篇,可以把兩個請求各自return Promise去做異步請求,最後用Promise.all()確認到兩邊資料都載入(兩個Promise都完成)後再去渲染畫面。

好的!我來去看看
感謝大大解答!

Zero皇 iT邦研究生 3 級 ‧ 2022-05-17 20:27:34 檢舉

/images/emoticon/emoticon12.gif

我要發表回答

立即登入回答