Last active
May 20, 2020 19:56
-
-
Save jenyayel/0b4164e407e43c8edffaffd61306aac8 to your computer and use it in GitHub Desktop.
Simple retry with constant backoff in nodejs with TypeScript
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
/** | |
* Performs operation and retries it in case either thrown | |
* exception or an optional `success` checker returns `false`. | |
* @param work The operation that need to perform | |
* @param checker Optional delegate to test whether the outcome of `work()` was successful operation | |
* @param retries An amount of retries to perform | |
* @param delayBetween An amount of milliseconds to wait between retries | |
*/ | |
export default async <TResult>( | |
work: () => TResult | Promise<TResult>, | |
checker: (result: TResult) => boolean = () => true, | |
retries = 3, | |
delayBetween = 500) => { | |
let attempt = 1; | |
while (true) { | |
console.debug(`Performing operation with retry, attempt: ${attempt}`); | |
try { | |
const result = await work(); | |
if (checker(result)) { | |
return result; | |
} | |
console.warn(`Failed to perform operation on attempt ${attempt}`, result); | |
} catch (error) { | |
console.error(`An error occurred when performing operation with retry on attempt ${attempt}`, error); | |
} | |
attempt++; | |
if (attempt <= retries) { | |
await delay(delayBetween); | |
} else { | |
break; | |
} | |
} | |
console.warn(`Giving up on retry after ${attempt} attempts`); | |
return undefined; | |
}; | |
const delay = (time = 1000) => new Promise((r) => setTimeout(() => r(), time)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use: