@chaisser/retry-async
v1.0.0
Published
Retry async functions with exponential backoff
Maintainers
Readme
🔄 @chaisser/retry-async
Retry async functions with exponential backoff, jitter, predicates, and more
✨ Features
- 🎯 Type-safe - Full TypeScript support with generics
- ⏱️ Exponential backoff - Configurable base, factor, and max delay
- 🎲 Jitter - Randomize delays to avoid thundering herd
- 🔍 Retry predicate - Only retry specific errors
- 📊 Result metadata - Track attempts and elapsed time
- 🔄 Retry forever - Keep trying until success
- 📦 Bulk retry - Retry multiple functions in parallel
- 🔧 Decorator - Wrap any async function with retry
- 📏 Fixed / Linear / Immediate - Multiple backoff strategies
- 🪶 Zero dependencies - Lightweight and tree-shakeable
- 🏎️ ESM + CJS - Dual module format support
📦 Installation
npm install @chaisser/retry-async
# or
yarn add @chaisser/retry-async
# or
pnpm add @chaisser/retry-async🚀 Quick Start
import { retry } from '@chaisser/retry-async';
// Basic retry (3 attempts, 1s exponential backoff)
const data = await retry(() => fetch('/api/data').then(r => r.json()));
// With options
const result = await retry(fn, {
attempts: 5,
delay: 500,
factor: 2,
maxDelay: 10000,
jitter: true,
});📖 What It Does
This package provides async retry utilities for JavaScript and TypeScript. It supports exponential backoff with configurable delay, factor, max delay, and jitter. Includes predicates for selective retries, callbacks for monitoring, result metadata, bulk retry, and multiple backoff strategies.
💡 Usage Examples
Basic Retry
import { retry } from '@chaisser/retry-async';
const data = await retry(
() => fetch('https://api.example.com/data').then(r => r.json()),
{ attempts: 3, delay: 1000 }
);With Retry Predicate
import { retry } from '@chaisser/retry-async';
const data = await retry(fn, {
attempts: 5,
retryIf: (err) => err instanceof TypeError, // only retry TypeErrors
});With onRetry Callback
import { retry } from '@chaisser/retry-async';
await retry(fn, {
attempts: 5,
onRetry: (err, attempt) => {
console.log(`Attempt ${attempt} failed:`, err.message);
},
});With Result Metadata
import { retryWithResult } from '@chaisser/retry-async';
const result = await retryWithResult(fn, { attempts: 5 });
console.log(result.value); // the resolved value
console.log(result.attempts); // number of attempts made
console.log(result.elapsed); // total ms elapsedWith Attempt Callback
import { retryWithCallback } from '@chaisser/retry-async';
await retryWithCallback(fn, (info) => {
console.log(`Attempt ${info.attempt} failed, retrying in ${info.delay}ms`);
}, { attempts: 5 });Retry Forever
import { retryForever } from '@chaisser/retry-async';
// Keeps retrying until success
const data = await retryForever(() => fetchData(), { delay: 2000 });Retryable Decorator
import { retryable } from '@chaisser/retry-async';
const fetchWithRetry = retryable(
(url: string) => fetch(url).then(r => r.json()),
{ attempts: 3, delay: 500 }
);
const data = await fetchWithRetry('/api/data');Bulk Retry
import { retryAll, retrySettled } from '@chaisser/retry-async';
// All must succeed
const results = await retryAll([
() => fetch('/api/a').then(r => r.json()),
() => fetch('/api/b').then(r => r.json()),
]);
// Tolerate failures
const settled = await retrySettled([fn1, fn2, fn3]);Backoff Strategies
import { retryFixed, retryLinear, retryImmediate } from '@chaisser/retry-async';
// Fixed delay (constant between retries)
await retryFixed(fn, 1000, 5);
// Linear backoff (delay * attempt)
await retryLinear(fn, { delay: 1000, attempts: 5 });
// No delay (immediate retry)
await retryImmediate(fn, 3);Delay Calculation
import { getDelay } from '@chaisser/retry-async';
getDelay(1, { delay: 100, factor: 2 }); // 100
getDelay(2, { delay: 100, factor: 2 }); // 200
getDelay(3, { delay: 100, factor: 2 }); // 400📚 API Reference
Core
| Function | Signature | Description |
|---|---|---|
| retry(fn, options?) | (Fn, RetryOptions?) → Promise<T> | Retry with exponential backoff |
| retryWithResult(fn, options?) | (Fn, RetryOptions?) → Promise<RetryResult<T>> | Retry with attempt/elapsed metadata |
| retryWithCallback(fn, onAttempt, options?) | (Fn, Callback, RetryOptions?) → Promise<T> | Retry with per-attempt callback |
RetryOptions
| Option | Type | Default | Description |
|---|---|---|---|
| attempts | number | 3 | Maximum number of attempts |
| delay | number | 1000 | Base delay in ms |
| maxDelay | number | 30000 | Maximum delay cap in ms |
| factor | number | 2 | Backoff multiplier |
| jitter | boolean | false | Randomize delay (50-100% range) |
| retryIf | (error) => boolean | — | Only retry when predicate returns true |
| onRetry | (error, attempt) => void | — | Callback on each retry |
RetryResult
| Field | Type | Description |
|---|---|---|
| value | T | The resolved value |
| attempts | number | Number of attempts made |
| elapsed | number | Total ms elapsed |
RetryAttempt (callback info)
| Field | Type | Description |
|---|---|---|
| attempt | number | Current attempt number |
| error | unknown | The error that caused the retry |
| delay | number | Delay before next attempt in ms |
Specialized
| Function | Description |
|---|---|
| retryForever(fn, options?) | Keep retrying until success (no attempt limit) |
| retryable(fn, options?) | Decorator that wraps a function with retry |
| retryAll(fns, options?) | Retry all functions in parallel |
| retrySettled(fns, options?) | Retry all, return settled results |
Backoff Strategies
| Function | Description |
|---|---|
| retryFixed(fn, delay, attempts) | Constant delay between retries |
| retryLinear(fn, options?) | Linear backoff |
| retryImmediate(fn, attempts) | No delay between retries |
Utility
| Function | Description |
|---|---|
| getDelay(attempt, options?) | Calculate delay for a given attempt number |
🔗 Related Packages
Explore our other utility packages in the @chaisser namespace:
- @chaisser/retry-async (this package) - Retry async functions with exponential backoff
- @chaisser/chunk-array - Split arrays into chunks
- @chaisser/string-wizard - Advanced string manipulation
- @chaisser/type-guard - Runtime type guards and validators
- @chaisser/uuid-v7 - Time-ordered UUID v7 generator
- @chaisser/wait-for - Promise-based wait utilities
- @chaisser/regex-humanizer - Regex to human-readable descriptions
- @chaisser/password-strength - Password strength checker
- @chaisser/human-time - Human-readable time formatting
- @chaisser/obj-path - Safe dot-notation object access
- @chaisser/debounce-throttle - Rate limiting utilities
- @chaisser/color-utils - Color conversion utilities
- @chaisser/deep-clone - Deep cloning functions
- @chaisser/array-group-by - Array grouping utilities
- @chaisser/merge-objects - Object merge utilities
- @chaisser/event-emitter - Typed event emitter
- @chaisser/unique-by - Array uniqueness utilities
- @chaisser/memoize - Function memoization
- @chaisser/base64-url - URL-safe base64 encoding
- @chaisser/ip-regex - IP address validation
🔒 License
MIT - Free to use in personal and commercial projects
👨 Developed by
Doruk Karaboncuk [email protected]
📄 Repository
- GitHub: @Chaisser
- NPM: @chaisser/retry-async
🤝 Contributing
Contributions are welcome! Feel free to:
- Report bugs
- Suggest new features
- Submit pull requests
- Improve documentation
📞 Support
For issues, questions, or suggestions, please reach out through:
- Email: [email protected]
- GitHub Issues: Create an issue
Made with ❤️ by @chaisser
