Skip to content

Instantly share code, notes, and snippets.

@gabrielpetersson
Created October 18, 2022 14:15
Show Gist options
  • Save gabrielpetersson/a0f8ad51e09f07c1c97899c8e0143c7b to your computer and use it in GitHub Desktop.
Save gabrielpetersson/a0f8ad51e09f07c1c97899c8e0143c7b to your computer and use it in GitHub Desktop.
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