Created
December 7, 2023 22:05
-
-
Save estelsmith/4ffd399e44f25d5618cd92b3c78b21b3 to your computer and use it in GitHub Desktop.
JavaScript Fetch w/ Timeout
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
/** | |
* A wrapper around the fetch api that will abort after a configurable amount of time has passed. | |
* | |
* @param {URL|string} input | |
* @param {RequestInit?} init | |
* @param {number?} providedTimeout | |
* @returns {Promise<Response>} | |
*/ | |
export default async function fetchTimeout(input, init, providedTimeout) { | |
const timeout = providedTimeout ?? config.timeouts.defaultTimeout; | |
const abortController = new AbortController(); | |
const timer = setTimeout(() => abortController.abort(), timeout); | |
const response = await fetch( | |
input, | |
{ | |
signal: abortController.signal, | |
...(init || {}) | |
} | |
); | |
clearTimeout(timer); | |
return response; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment