美文网首页
fetch设置超时

fetch设置超时

作者: 与你清欢_李 | 来源:发表于2019-05-06 17:25 被阅读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);
      });
    
    

    相关文章

      网友评论

          本文标题:fetch设置超时

          本文链接:https://www.haomeiwen.com/subject/seudoqtx.html