lstoryc / lstoryc.github.io

My Blog
2 stars 0 forks source link

Q10. 请求超时处理 #13

Open lstoryc opened 4 years ago

lstoryc commented 4 years ago

1. 基于XMLHTTPRequest

var xhr = new XMLHttpRequest();
xhr.open("GET", "/server", true);
xhr.timeout = 2000;
xhr.onload = function () {
  console.warn("请求完成");
};
xhr.ontimeout = function (e) {
  console.error("超时啦");
};
xhr.send(null);

2. 基于Promise和Fetch

const fetch2 = (url, fetchParams = {}, delay = 6000) => {
  const abortController = new AbortController();
  const signal = abortController.signal;
  const options = { ...fetchParams, signal };

  console.warn("delay: ", delay);
  return Promise.race([
    fetch(url, options),
    new Promise((res, rej) => {
      setTimeout(()=>{
        console.warn('-----',delay);
        abortController.abort();
        rej("Timeout");
      }, delay);
    }),
  ]);
};

fetch2("/a/1190000021322450",{}, 0).catch((e) => console.warn(e));