Skip to content

Instantly share code, notes, and snippets.

@Alex1990
Last active December 28, 2019 19:29
Show Gist options
  • Save Alex1990/866d75336677118a9ca0c609354c26da to your computer and use it in GitHub Desktop.
Save Alex1990/866d75336677118a9ca0c609354c26da to your computer and use it in GitHub Desktop.
Retry a function the specified times
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
}
@Alex1990
Copy link
Author

Alex1990 commented Oct 22, 2019

Example:

async function foo (k) {
  const n = Math.random()
  console.log(`n: ${n}, k: ${k}`)
  if (n < k) {
    throw new Error(`must not be less than ${k}`)
  }
  return n
}

console.log(retry(foo, 3, 0.5))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment