Skip to content

Instantly share code, notes, and snippets.

@antomor
Last active October 21, 2020 19:30
Show Gist options
  • Save antomor/eb35bb94065c1d6ec914ef5c1a20f829 to your computer and use it in GitHub Desktop.
Save antomor/eb35bb94065c1d6ec914ef5c1a20f829 to your computer and use it in GitHub Desktop.
A js function that tries to execute a function n times, waiting before the next attempt, and with the possibility to set a initial delay.
const wait = (milliSeconds) => {
return new Promise((resolve) => setTimeout(() => resolve(), milliSeconds));
};
const retry = ({fn, maxRetries, initialDelayMs, intervalMs}) => {
// first attempt after the initial delay
let attempts = wait(initialDelayMs);
if ( maxRetries > 0) {
attempts = attempts.then(() => fn());
}
// the attempts after the first will be executed after waiting for the milliseconds specified
for (let i = 1; i < maxRetries; i++) {
attempts = attempts.catch(() => wait(intervalMs).then(() => fn()));
}
attempts = attempts.catch(() => {
throw new Error(`Failed retrying ${maxRetries} times`);
});
return attempts;
};
const hello = () => console.log("Hello");
// Simulate a number of attempts
const resolveAfterTimes = (times) => {
let index = 0;
return () => {
if (index >= times-1) {
return Promise.resolve();
}
index++;
return Promise.reject();
}
}
// it resolves after 5 times
const resolveAfter5Times = resolveAfterTimes(5);
retry({
fn:resolveAfter5Times,
maxRetries: 5,
initialDelayMs: 200,
intervalMs: 200
}).then(() => hello()).catch((err) => console.error(err));
// or in async/await context
try {
await retry({
fn:resolveAfter,
maxRetries: 5,
initialDelayMs: 200,
intervalMs: 200
});
hello();
} catch(error) {
console.error(error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment