Skip to content

Instantly share code, notes, and snippets.

@chand1012
Last active April 14, 2023 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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