Last active
September 28, 2024 13:28
-
-
Save drwpow/866e10915e6222f9198923592e3236f5 to your computer and use it in GitHub Desktop.
Fetch retry with timeout
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
/** | |
* fetch() with retries | |
* @param {string} url URL to fetch | |
* @param {object} options All options required | |
* @param {number} options.timeout Max timeout, in milliseconds (default: 5000) | |
* @param {retries} options.retries Max number of retries (default: 2) | |
*/ | |
async function fetchWithRetry(url, { timeout, retries } = { timeout: 5000, retries: 2 }) { | |
let data; | |
let controller; | |
for (let n = 0; n <= retries; n++) { | |
let timer; | |
try { | |
// 1. create new AbortController | |
if (!controller) controller = new AbortController(); | |
// 2. time out after 5s | |
timer = setTimeout(() => { | |
controller.abort(); // break current loop | |
}, timeout); | |
// 3. fetch | |
data = await fetch(url, { signal: controller.signal }).then((data) => data.json()); | |
// 4. clear timeout if successful | |
clearTimeout(timer); | |
return data; | |
} catch (err) { | |
clearTimeout(timer); // clear timeout just for safety | |
// TODO: handle HTTP errors here, or in fetch(). | |
} | |
} | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for that Gist, it really helped me!
I have a few suggestions for improvement.
RequestInit
object to the function and pass it on tofetch
with the spread operator, along with theAbortController
signal. This makes the function behave more like the originalfetch
, so it can basically be used as a drop-in replacement.AbortController
instance for each request, because otherwise, every subsequent retry will be immediately aborted. This is at least the behavior that I see in the latest version of Firefox (I haven't tested any other browsers yet).DOMException
(which happens when aborting), so the error handling that happens outside the function behaves more or less like a normalfetch
call.