Last active
December 28, 2019 19:29
-
-
Save Alex1990/866d75336677118a9ca0c609354c26da to your computer and use it in GitHub Desktop.
Retry a function the specified times
This file contains 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
async function retry(fn, times = 0, ...args) { | |
if (typeof times !== 'number') throw new Error('times must be a number') | |
if (times < 0) throw new Error('times must not be less than 0') | |
const totalTimes = times + 1 | |
let result | |
let firstError | |
let i = 0 | |
for (; i < totalTimes; i++) { | |
try { | |
result = await fn(...args) | |
break | |
} catch (err) { | |
if (!firstError) firstError = err | |
} | |
} | |
if (i === totalTimes && firstError) throw firstError | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: