Skip to content

Instantly share code, notes, and snippets.

@gabryon99
Created November 12, 2020 09:34
Show Gist options
  • Save gabryon99/4aa8cf8206c9b6a997ff1d324843299b to your computer and use it in GitHub Desktop.
Save gabryon99/4aa8cf8206c9b6a997ff1d324843299b to your computer and use it in GitHub Desktop.
Timeout Fetch
class RequestTimeoutError extends Error {
constructor(message) {
super(message);
this.name = "RequestTimeout";
}
}
const timeoutFetch = async (url, params = {}, timeout = 0) => {
// create a new abort controller to handle timeout
const abortController = new AbortController();
// if timeout is zero we are doing a normal fetch request
if (timeout !== 0) {
setTimeout(() => { abortController.abort() }, timeout);
}
try {
// try to fetch data from the URL
const request = await fetch(url, Object.assign(params, { signal: abortController.signal }));
return request;
}
catch (e) {
// if the timeout has expired then an AbrotError is thrown
// then we throw a RequestTimeoutErrror
if (e.name === "AbortError") {
throw new RequestTimeoutError("Timeout has expired!");
}
// otherwise we throw a fetch exception
throw e;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment