实现Fetch 请求扩展超时功能

发布时间 2023-08-23 10:18:30作者: 天宁哦

要实现基本的超时功能其实很简单,只需要使用 AbortController 这个 API,如果你不熟悉它,可以点击链接了解一下

/**
 * @description: 创建一个 fetch 函数
 * @param {*} timeout: 传入超时的时间
 * @return {*} 返回一个新的 fetch 函数
 */
function createFetch(timeout) {
  // 返回一个新的 fetch 函数
  return (resource, options) => {
    // 定义一个终止器
    let controller = new AbortController();
    // options 配置默认值
    options = options || {};
    // 向原来的 fetch 配置中加入 signal
    options.signal = controller.signal;
    setTimeout(() => {
      // 当时间到达之后运行 abort
      controller.abort();
    }, timeout);
    return fetch(resource, options);
  };
}
 
// 如果我们不想使用超时功能就可以直接使用 fetch
fetch();
 
// 如果我们想要使用超时功能就使用 createFetch 创建一个新的 fetch
createFetch(3000)("url", {});