sibelius
10/4/2018 - 1:11 PM

how to handle api timeout using fetch

how to handle api timeout using fetch

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);