Skip to content

Instantly share code, notes, and snippets.

@moritzsalla
Created August 31, 2023 07:50
Show Gist options
  • Save moritzsalla/f7076ae8c5e0d9a63b66c2f3d85e07f9 to your computer and use it in GitHub Desktop.
Save moritzsalla/f7076ae8c5e0d9a63b66c2f3d85e07f9 to your computer and use it in GitHub Desktop.
const TIMEOUT_DURATION_MS = 3000;
/**
* Fetches a resource with a timeout.
*
* @param input - The resource to fetch.
* @param init - The options for the fetch.
* @param timeoutDuration - The timeout duration in milliseconds.
*
* @returns A promise that resolves to the response of the fetch.
*
* @throws {Error} - If an exception occurs during the fetch.
*/
export const timeoutFetch = async (
input: RequestInfo,
init?: RequestInit,
timeoutDuration: number = TIMEOUT_DURATION_MS
) => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutDuration);
try {
return await fetch(input, init);
} catch (error) {
throw error;
} finally {
clearTimeout(timeoutId);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment