Created
October 4, 2018 13:11
-
-
Save sibelius/624ebc0e1a7e4784140b78f4b214e9f5 to your computer and use it in GitHub Desktop.
how to handle api timeout using fetch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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