Skip to content

retry

Retry an async function when it fails

535 bytes

Usage

The retry function runs an async function and retries it if it fails. You can specify how many times to retry, how long to wait between retries, and whether to use exponential backoff.

Options

  • times is the maximum number of times to retry (default: 3)
  • delay is milliseconds to sleep between retries
  • backoff is a function called to calculate the delay between retries
    • It receives the attempt number (starting with 1) and returns the delay in milliseconds.
  • signal (v12.3.0+) allows you to pass an AbortController.signal to interrupt the retry operation
import * as _ from 'radashi'
const api = {
users: {
async list() {
if (Math.random() < 0.5) {
throw new Error('Random error')
}
return []
},
},
}
await _.retry({}, api.users.list) // try 3 times before failing
await _.retry({ times: 10 }, api.users.list) // try 10 times before failing
await _.retry({ times: 2, delay: 1000 }, api.users.list) // try 2 times with 1 second delay
// exponential backoff
await _.retry({ backoff: i => 10 ** i }, api.users.list) // try 3 times with 10, 100, 1000 ms delay

Interrupting

If a signal is passed, the retry operation can be interrupted. When the signal is aborted, retry’s promise will reject with a DOMException (even in Node.js) with the message This operation was aborted and name AbortError.

import * as _ from 'radashi'
const abortController = new AbortController()
const signal = abortController.signal
const promise = _.retry({ times: 3, delay: 1000, signal }, api.users.list)
// To stop retrying immediately:
abortController.abort()
try {
await promise
} catch (err) {
if (err.message === 'This operation was aborted') {
console.log('Retry operation was aborted')
}
}