Created
February 1, 2019 14:48
-
-
Save attila/0b76a36eb56f0afbc35654e5dab76ebb to your computer and use it in GitHub Desktop.
Retry with delays
This file contains hidden or 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
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