Created
August 31, 2023 07:50
-
-
Save moritzsalla/f7076ae8c5e0d9a63b66c2f3d85e07f9 to your computer and use it in GitHub Desktop.
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
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