Created
January 6, 2022 08:24
-
-
Save KrofDrakula/b14393917c52aed72510544abcaf7144 to your computer and use it in GitHub Desktop.
Fetch with timeout and optional cancellation
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
export const fetchWithTimeout = ( | |
uri: RequestInfo, | |
timeout: number, | |
options: RequestInit = {} | |
): [Promise<Response>, () => void] => { | |
const controller = new AbortController(); | |
const timer = setTimeout(controller.abort, timeout); | |
const promise = fetch(uri, { ...options, signal: controller.signal }); | |
promise.finally(() => clearTimeout(timer)); | |
return [promise, controller.abort]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment