Last active
April 13, 2024 20:36
-
-
Save dillonstreator/4f030db04dfede9a17f6c97a8cd1b7f3 to your computer and use it in GitHub Desktop.
`fetch` wrapper with timeout
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
class TimeoutError extends Error { | |
error: unknown; | |
constructor(timeoutMs: number, error: unknown) { | |
super(`Operation timed out after ${timeoutMs}ms`); | |
this.name = 'TimeoutError'; | |
this.error = error; | |
} | |
} | |
const fetchTimeout = async ( | |
url: RequestInfo | URL, | |
{ | |
timeoutMs = 5000, | |
fetcher = fetch, | |
...options | |
}: RequestInit & { timeoutMs?: number; fetcher?: typeof fetch } = {} | |
): Promise<Response> => { | |
const controller = new AbortController(); | |
let timedOut = false; | |
const timeout = setTimeout(() => { | |
timedOut = true; | |
controller.abort(); | |
}, timeoutMs); | |
const handleOgAbort = () => { | |
clearTimeout(timeout); | |
controller.abort(); | |
}; | |
options.signal?.addEventListener('abort', handleOgAbort); | |
const cleanup = () => { | |
clearTimeout(timeout); | |
options.signal?.removeEventListener('abort', handleOgAbort); | |
}; | |
try { | |
const response = await fetcher(url, { | |
...options, | |
signal: controller.signal, | |
}); | |
return response; | |
} catch (error) { | |
throw timedOut ? new TimeoutError(timeoutMs, error) : error; | |
} finally { | |
cleanup(); | |
} | |
}; | |
const ab = new AbortController(); | |
setTimeout(() => ab.abort(), 5); | |
Promise.allSettled([ | |
fetchTimeout('https://api.github.com', { timeoutMs: 15 }), | |
fetchTimeout('https://api.github.com', { timeoutMs: 4, signal: ab.signal }), | |
fetchTimeout('https://api.github.com', { timeoutMs: 5, signal: ab.signal }), | |
fetchTimeout('https://api.github.com', { timeoutMs: 6, signal: ab.signal }), | |
fetchTimeout('https://api.github.com', { timeoutMs: 250 }), | |
]).then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A simpler approach that uses
AbortSignal.any()
andAbortSignal.timeout()
methods: