retryPromise
Utility function to retry asynchronous operations with configurable retry logic.
Installation
bash
npx kuro-ui add retryPromise
bash
npx github:Bartek-Nowak/Kuro add retryPromise
📦 Usage
ts
import { retryPromise } from '@/utils/kuro/retryPromise'
const fetchData = async () => {
const res = await fetch('https://api.example.com/data')
if (!res.ok) throw new Error('Request failed')
return res.json()
}
retryPromise(fetchData, {
retries: 5,
delay: 1000,
shouldRetry: (err, attempt) => {
console.warn(`Attempt ${attempt} failed: ${err.message}`)
return true // Add your own logic here, e.g., retry only for 5xx errors
},
})
.then(console.log)
.catch(console.error)
🧠 Description
retryPromise takes an async function and retries it on failure based on the provided configuration.
This is useful for:
Fetching data from unreliable APIs
Retrying operations that might fail due to temporary issues (e.g., network)
🧩 Signature
ts
function retryPromise<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>
⚙️ RetryOptions
ts
type RetryOptions = {
retries?: number // Number of attempts before giving up (default: 3)
delay?: number // Delay in milliseconds between retries (default: 500)
shouldRetry?: (error: any, attempt: number) => boolean
// Custom retry condition (default: always true)
}
retries
: How many times to retry before failing.
delay
: How long to wait (in ms) between retries.
shouldRetry
: Function that decides whether to continue retrying. Receives the error and the attempt number.
✅ Example
Retry a network request up to 5 times, with 1 second between each try:
ts
retryPromise(
() =>
fetch('/api/data').then((r) => {
if (!r.ok) throw new Error('Failed')
return r.json()
}),
{
retries: 5,
delay: 1000,
shouldRetry: (err, attempt) => {
return err.message.includes('Failed')
},
},
)