Skip to content

Instantly share code, notes, and snippets.

@KrofDrakula
Created January 6, 2022 08:24
Show Gist options
  • Save KrofDrakula/b14393917c52aed72510544abcaf7144 to your computer and use it in GitHub Desktop.
Save KrofDrakula/b14393917c52aed72510544abcaf7144 to your computer and use it in GitHub Desktop.
Fetch with timeout and optional cancellation
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