Skip to content

Instantly share code, notes, and snippets.

@attila
Created February 1, 2019 14:48
Show Gist options
  • Save attila/0b76a36eb56f0afbc35654e5dab76ebb to your computer and use it in GitHub Desktop.
Save attila/0b76a36eb56f0afbc35654e5dab76ebb to your computer and use it in GitHub Desktop.
Retry with delays
const operation = () => new Promise((resolve, reject) => {
if (Math.random() > 0.8) {
resolve('all good');
} else {
reject(new Error('failure'));
}
});
const pause = duration => new Promise(resolve => setTimeout(resolve, duration));
const doWithRetries = (action, retries, delay) => {
return new Promise((resolve, reject) => {
action.call()
.catch(() => {
console.log('failed on run, retries: ', retries);
if (retries > 1) {
resolve(pause(delay)
.then(() => doWithRetries(action, retries - 1, delay)));
} else {
reject(new Error('++ final retry failed'));
}
})
.then(result => {
resolve(result);
});
});
};
const doIt = async () => {
try {
const result = await doWithRetries(operation, 10, 250);
console.log('+ success, result:', result);
} catch (err) {
console.error('+ failed', err)
}
};
doIt();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment