Skip to content

Instantly share code, notes, and snippets.

@imaginamundo
Last active November 15, 2022 16:14
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 imaginamundo/88f54c97bb154044350ad831aaf4eb30 to your computer and use it in GitHub Desktop.
Save imaginamundo/88f54c97bb154044350ad831aaf4eb30 to your computer and use it in GitHub Desktop.
A wrapper for fetch with timeout using abort controller and a specific timeout error with url and status.
const DEFAULT_TIMEOUT = 3000;
function request(resource, options = {}) {
const { timeout = DEFAULT_TIMEOUT } = options;
return fetch(resource, { ...options, signal: AbortSignal.timeout(timeout) });
}
export default request;
interface RequestOptions extends RequestInit {
timeout?: number;
}
const DEFAULT_TIMEOUT = 3000;
function request(
resource: string | Request | URL,
options: RequestOptions | undefined = {}
): Promise<Response> {
const { timeout = DEFAULT_TIMEOUT } = options;
delete options.timeout;
return fetch(resource, { ...options, signal: AbortSignal.timeout(timeout) });
}
export default request;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment