Skip to content

Instantly share code, notes, and snippets.

@jenyayel
Last active May 20, 2020 19:56
Show Gist options
  • Save jenyayel/0b4164e407e43c8edffaffd61306aac8 to your computer and use it in GitHub Desktop.
Save jenyayel/0b4164e407e43c8edffaffd61306aac8 to your computer and use it in GitHub Desktop.
Simple retry with constant backoff in nodejs with TypeScript
/**
* 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));
@jenyayel
Copy link
Author

How to use:

import retry from './retry';

await retry(() => console.log('Foo'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment