This library exports a
retry(...) function that can be used to invoke
a function that returns a
Promise multiple times until returned
Promise is resolved or the max number of attempts is reached.
The delay between each attempt is configurable and allows multiple retry strategies.
The following features are supported:
- Fixed delay between attempts
- Exponential backoff
- Exponential backoff with jitter
- Abort retries early
- Abort due to timeout
- Error handler for each attempt
npm install @lifeomic/attempt --save
yarn add @lifeomic/attempt
Node.js / CommonJS:
const retry = retry;
ES6 / TypeScript
tryconst result = await;catch err// If the max number of attempts was exceeded then `err`// will be the last error that was thrown.//// If error is due to timeout then `err.code` will be the// string `ATTEMPT_TIMEOUT`.
options argument is optional, and when absent the default values
are assigned. All times/durations are in milliseconds.
The following object shows the default options:
delay: 200maxAttempts: 3initialDelay: 0minDelay: 0maxDelay: 0factor: 0timeout: 0jitter: falsehandleError: nullhandleTimeout: nullbeforeAttempt: nullcalculateDelay: null
await then you will need to
use a transpiler such as
to your target environment.
The delay between each attempt in milliseconds. You can provide a
factorto have the
intialDelayis the amount of time to wait before making the first attempt. This option should typically be
0since you typically want the first attempt to happen immediately.
maxDelayoption is used to set an upper bound for the delay when
factoris enabled. A value of
0can be provided if there should be no upper bound when calculating delay.
factoroption is used to grow the
delayexponentially. For example, a value of
2will cause the delay to double each time. A value of
3will cause the delay to triple each time. Fractional factors (e.g.
1.5) are also allowed.
The following formula is used to calculate delay using the factor:
delay = delay * Math.pow(factor, attemptNum)
The maximum number of attempts or
0if there is no limit on number of attempts.
A timeout in milliseconds. If
timeoutis non-zero then a timer is set using
setTimeout. If the timeout is triggered then future attempts will be aborted.
handleTimeoutfunction can be used to implement fallback functionality.
truethen the calculated delay will be a random integer value between
minDelayand the calculated delay for the current iteration.
The following formula is used to calculate delay using
delay = Math.random() * (delay - minDelay) + minDelay
minDelayis used to set a lower bound of delay when
jitteris enabled. This property has no effect if
(err, context, options) => void
handleErroris a function that will be invoked when an error occurs for an attempt. The first argument is the error and the second argument is the context.
(context, options) => Promise | void
handleTimeoutis invoked if a timeout occurs when using a non-zero
handleTimeoutfunction should return a
Promisethat will be the return value of the
(context, options) => void
beforeAttemptfunction is invoked before each attempt. Calling
context.abort()will abort the attempt and stop retrying.
(context, options) => Number
calculateDelayfunction can be used to override the default delay calculation. Your provided function should return an integer value that is the calculated delay for a given attempt.
Information in the provided
optionsarguments should be used in the calculation.
calculateDelayis provided, any option that is used to calculate delay (
factor, etc.) will be ignored.
context has the following properties:
A zero-based index of the current attempt number (
The number of attempts remaining. The initial value is
() => void
abortfunction can be called when handling an error via
beforeAttemptfunction is invoked. The abort function should be used to prevent any further attempts in cases when an error indicates that we should not retry.
For example, an HTTP request that returns an HTTP error code of
400(Bad Request) should not be retried because there is a problem with the input (and retrying will not fix this). However, a request that returns
504(Gateway Timeout) should be retried because it might be a temporary problem.
Retry with defaults
// Try the given operation up to 3 times with a delay of 200 between// each attemptconst result = await;
Stop retrying if an error indicates that we should not retry
// Try the given operation update to 4 times. The initial delay will be 0// and subsequent delays will be 200, 400, 800const result = await;
Retry with exponential backoff
// Try the given operation update to 4 times. The initial delay will be 0// and subsequent delays will be 200, 400, 800 (delay doubles each time due// to factor of `2`)const result = await;
Retry with exponential backoff and max delay
// Try the given operation up to 5 times. The initial delay will be 0// and subsequent delays will be 200, 400, 500, 500 (capped at `maxDelay`)const result = await;
Retry with exponential backoff, jitter, min delay, and max delay
// Try the given operation 3 times. The initial delay will be 0// and subsequent delays will be in the following range:// - 100 to 200// - 100 to 400// - 100 to 500 (capped at `maxDelay`)// - 100 to 500 (capped at `maxDelay`)const result = await;
Stop retrying if there is a timeout
// Try the given operation up to 5 times. The initial delay will be 0// and subsequent delays will be 200, 400, 800, 1600.//// If an attempt fails to complete after 1 second then the retries// are aborted and error with `code` `ATTEMPT_TIMEOUT` is thrown.const result = await;
Stop retrying if there is a timeout but provide a fallback
// Try the given operation up to 5 times. The initial delay will be 0// and subsequent delays will be 200, 400, 800, 1600.//// If an attempt fails to complete after 1 second then the retries// are aborted and the `handleTimeout` implements some fallback logic.const result = await;