Created
October 18, 2022 14:15
-
-
Save gabrielpetersson/a0f8ad51e09f07c1c97899c8e0143c7b to your computer and use it in GitHub Desktop.
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
export const fetchRetry = async ( | |
fetch: () => Promise<Response>, | |
maxTries: number = 4 | |
): Promise<Response | "error"> => { | |
for (let tries = 0; tries < maxTries; tries++) { | |
if (tries !== 0) { | |
await wait(Math.pow(2, tries + 1) * 1000); | |
} | |
try { | |
const response = await fetch(); | |
if (response.ok) { | |
return response; | |
} | |
console.error( | |
`Attempt: ${tries + 1} of ${maxTries}` | |
); | |
} catch (e) { | |
console.error(`Network error. Attempt: ${tries + 1} of ${maxTries}`); | |
} | |
} | |
return "error"; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment