Created
January 18, 2021 12:47
-
-
Save jasdeepkhalsa/95f6d51fa8c00ef625fa21dab68d6164 to your computer and use it in GitHub Desktop.
Exponential backoff retry strategy for async
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
// 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