Fetch設置超時時間

/**
 *
 *
 * @param {string} url
 * @param {number} 超時時間
 * @returns
 */
function request(url,wait=30) {
  return new Promise((resolve, reject) => {
    let status = 0; // 0 等待 1 完成 2 超時
    let timer = setTimeout(() => {
      if (status === 0) {
        status = 2;
        timer = null;
        reject("超時");
      }
    }, 3000);
    fetch(url, {
      headers: {
        "content-type": "application/json"
      }
    })
      .then(res => res.json())
      .then(res => {
        if (status !== 2) {
          clearTimeout(timer);
          resolve(res);
          timer = null;
          status = 1;
        }
      });
  });
}

request("/test")
  .then(res => {
    document.body.innerHTML =
      typeof res !== "string" ? JSON.stringify(res) : res;
  })
  .catch(err => {
    console.log("err", err);
  });

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章