Created
June 20, 2016 16:49
-
-
Save timdp/cd4480c573875d03fb5636a5a3746cce to your computer and use it in GitHub Desktop.
retry with async/await
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
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