为 fetch 添加 timeout 机制

修改了fetch-timeout 的代码,增加了取消,完整列出来:

export async function fetchWithTimeout(url: RequestInfo, options: RequestInit | undefined, timeout: number, error: string): Promise<Response> {
  let controller = new AbortController();
  let signal = controller.signal;
  error = error || 'Timeout error';
  options = options || {};
  options.signal = signal;
  timeout = timeout || 10000;
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(new Response("timeout", { status: 504, statusText: "timeout " }));
      controller.abort();
    }, timeout);
    (window as any).fetch(url, options).then(resolve, reject);
  });
}
posted @ 2021-06-17 17:35  花园小花匠  阅读(372)  评论(0编辑  收藏  举报