Last active
September 20, 2024 13:52
-
-
Save chand1012/43c187e650cc1fc3775f296817053f97 to your computer and use it in GitHub Desktop.
Deno fetch with optional timeout parameter. If the request takes longer than 10 seconds (or whatever you set it to), throws an error.
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
// LICENSE: https://chand1012.mit-license.org | |
const fetchWithTimeout = (url: string, options: RequestInit, timeout: number = 10000): Promise<any> => { | |
return new Promise(async (resolve, reject) => { | |
const controller = new AbortController(); | |
const signal = controller.signal; | |
const timer = setTimeout(() => { | |
controller.abort(); | |
reject(new Error("Request timed out")); | |
}, timeout); | |
try { | |
const response = await fetch(url, { ...options, signal }); | |
clearTimeout(timer); | |
resolve(response); | |
} catch (error) { | |
clearTimeout(timer); | |
reject(error); | |
} | |
}); | |
}; | |
export default fetchWithTimeout; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment