javascript 如何使用fetch处理api超时

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 如何使用fetch处理api超时相关的知识,希望对你有一定的参考价值。

function TimeoutError(error) {
  this.name = 'TimeoutError';
  this.error = error;
}
TimeoutError.prototype = Object.create(Error.prototype);

export const isTimeoutError = (err: Error) => {
  return err instanceof TimeoutError;
};

export const timeout = (ms: number): Function => (f: Function): Function => (
  url: string,
  args: ExtractReturn<typeof buildOptions>,
): Promise<*> =>
  new Promise(async (resolve, reject) => {
    setTimeout(() => {
      reject(new TimeoutError(prettyFormat(args)));
    }, ms);
    f(url, args).then(resolve, reject);
  });
  
  const fetchWithTimeout = timeout(defaultTimeout)(fetch);

以上是关于javascript 如何使用fetch处理api超时的主要内容,如果未能解决你的问题,请参考以下文章