Skip to content

Instantly share code, notes, and snippets.

@chand1012
Last active September 20, 2024 13:52
Show Gist options
  • Save chand1012/43c187e650cc1fc3775f296817053f97 to your computer and use it in GitHub Desktop.
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.
// 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