A flexible, functional-style async retry utility with composable predicates and delay strategies — designed to simplify robust retry logic in JavaScript/TypeScript.
- Composable: Separate your retry exit conditions (
untilFn
) and delay strategies (getNextTickFn
) for maximum flexibility. - Type-safe: Built with TypeScript for strong typing and developer confidence.
- Pre-built predicates & delay functions: Includes useful defaults like
untilHttpStatusOk
,untilMaxAttempts
,withJitter
,advanceFirstAttempt
,withExponentialDecay
, andeveryNSeconds
. - Zero dependencies: Lightweight and easy to integrate.
- Tested and reliable: Comprehensive test coverage with Jest.
npm install retry-fp
# or
yarn add retry-fp
import retry, {
untilFirst,
untilHttpStatusOk,
untilMaxAttempts,
withExponentialDecay,
advanceFirstAttempt,
} from 'retry-fp'
// Your async work function (e.g., HTTP request)
async function fetchData(): Promise<{ status: number; data?: any }> {
// simulate fetch logic here
}
// Retry until HTTP status is 200 or max 5 attempts
// With exponentially backoff with a jitter to avoid the thundering heard problem
const result = await retry(
fetchData,
untilFirst(untilHttpStatusOk(), untilMaxAttempts(5)),
advanceFirstAttempt(withJitter()(withExponentialDecay(500)))
)
if (result.error) {
console.error('Failed after retries:', result.error)
} else {
console.log('Success:', result.workOutput)
}
import retry, {
untilForever,
withExponentialDecay,
advanceFirstAttempt,
} from 'retry-fp'
let latestResult
// Poll for data every 10 seconds
const result = retry(
async () => {
const response = await fetchData()
latestResult = response
return response
},
untilForever(),
everyNSeconds(10),
)
Tests use Jest with fake timers to simulate delay and retries. Run tests with:
yarn test
Contributions, issues, and feature requests are welcome! Feel free to check issues page or submit a pull request.