Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created October 4, 2018 13:11
Show Gist options
  • Save sibelius/624ebc0e1a7e4784140b78f4b214e9f5 to your computer and use it in GitHub Desktop.
Save sibelius/624ebc0e1a7e4784140b78f4b214e9f5 to your computer and use it in GitHub Desktop.
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment