Function retry
- retry<T>(fn, options?): Promise<T>
Type Parameters
Parameters
- fn: (() => Promise<T>) | (() => T)
The function to retry.
Optionaloptions: RetryOptionsAdditional options.
Returns Promise<T>
The promise that resolves with the value returned by the function to retry.
Example: Example configuration 1
import { retry } from "@std/async/retry";
const req = async () => {
// some function that throws sometimes
};
// Below resolves to the first non-error result of `req`
const retryPromise = await retry(req, {
multiplier: 2,
maxTimeout: 60000,
maxAttempts: 5,
minTimeout: 100,
jitter: 1,
});Example: Example configuration 2
import { retry } from "@std/async/retry";
const req = async () => {
// some function that throws sometimes
};
// Make sure we wait at least 1 minute, but at most 2 minutes
const retryPromise = await retry(req, {
multiplier: 2.34,
maxTimeout: 80000,
maxAttempts: 7,
minTimeout: 1000,
jitter: 0.5,
});- fn: (() => Promise<T>) | (() => T)
Calls the given (possibly asynchronous) function up to
maxAttemptstimes. Retries as long as the given function throws. If the attempts are exhausted, throws aRetryErrorwithcauseset to the inner exception.The backoff is calculated by multiplying
minTimeoutwithmultiplierto the power of the current attempt counter (starting at 0 up tomaxAttempts - 1). It is capped atmaxTimeouthowever. How long the actual delay is, depends onjitter.When
jitteris the default value of1, waits between two attempts for a randomized amount between 0 and the backoff time. With the default options the maximal delay will be15s = 1s + 2s + 4s + 8s. If all five attempts are exhausted the mean delay will be9.5s = ½(4s + 15s).When
jitteris0, waits the full backoff time.