Created
November 12, 2020 09:34
-
-
Save gabryon99/4aa8cf8206c9b6a997ff1d324843299b to your computer and use it in GitHub Desktop.
Timeout Fetch
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
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