Skip to content

Instantly share code, notes, and snippets.

@jasdeepkhalsa
Created January 18, 2021 12:47
Show Gist options
  • Save jasdeepkhalsa/95f6d51fa8c00ef625fa21dab68d6164 to your computer and use it in GitHub Desktop.
Save jasdeepkhalsa/95f6d51fa8c00ef625fa21dab68d6164 to your computer and use it in GitHub Desktop.
Exponential backoff retry strategy for async
// General purpose Rejection-based retrying
// Source: https://advancedweb.hu/how-to-implement-an-exponential-backoff-retry-strategy-in-javascript/
const wait = (ms) => new Promise((res) => setTimeout(res, ms));
const maybeFail = (successProbability, result, error) => new Promise((res, rej) => Math.random() < successProbability ? res(result) : rej());
const maybeFailingOperation = async () => {
await wait(10);
return maybeFail(0.1, "result", "error");
}
const callWithRetry = async (fn, depth = 0) => {
try {
return await fn();
}catch(e) {
if (depth > 7) {
throw e;
}
await wait(2 ** depth * 10);
return callWithRetry(fn, depth + 1);
}
}
const result = await callWithRetry(maybeFailingOperation);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment