-
-
Save tgmarinho/349950a4ddf47128609a4adb786621d5 to your computer and use it in GitHub Desktop.
how to handle api timeout using fetch
This file contains hidden or 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