Skip to content

Instantly share code, notes, and snippets.

@timdp
Created June 20, 2016 16:49
Show Gist options
  • Save timdp/cd4480c573875d03fb5636a5a3746cce to your computer and use it in GitHub Desktop.
Save timdp/cd4480c573875d03fb5636a5a3746cce to your computer and use it in GitHub Desktop.
retry with async/await
import delay from 'delay'
const createAttempter = (worker) => async () => {
let retval, error, time
const startTime = Number(new Date())
try {
retval = await worker()
} catch (err) {
error = err
}
time = new Date() - startTime
return {retval, error, time}
}
const retry = async (work, {interval, attempts}) => {
const attempt = createAttempter(work)
let result = await attempt()
let attemptCount = 1
while (result.error != null && attemptCount < attempts) {
if (result.time < interval) {
await delay(interval - result.time)
}
result = await attempt()
++attemptCount
}
if (result.error != null) {
throw result.error
}
return result.retval
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment