fetch设置超时

2019-05-06  本文已影响0人  与你清欢_李
/**
 *
 *
 * @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);
  });

上一篇下一篇

猜你喜欢

热点阅读