API Reference / @evolu/common / Promise / retry
Function: retry()
function retry<T, E>(fn, options): Promise<Result<T,
| RetryAbortError
| RetryError<E>>>;
Defined in: packages/common/src/Promise.ts:179
Executes a function with retry logic using exponential backoff and jitter.
Example with Result-based API
interface ApiError {
type: "ApiError";
statusCode: number;
}
const fetchData = async (
url: string,
): Promise<Result<Data, ApiError>> => {
// Implementation that returns Result
};
const result = await retry(
async () => fetchData("https://api.example.com/data"),
{
maxRetries: 5,
initialDelay: 200,
// Only retry on specific status codes
retryable: (error) =>
error.type === "ApiError" && [429, 503].includes(error.statusCode),
},
);
if (!result.ok) {
if (result.error.type === "RetryAbortError") {
console.log("Operation was aborted");
} else {
console.log(`Failed after ${result.error.attempts} attempts`);
}
return;
}
// Use result.value
Example with tryAsync for exception-based API
interface FetchError {
type: "FetchError";
message: string;
}
const controller = new AbortController();
const result = await retry(
async () =>
tryAsync(
async () => {
const response = await fetch("https://api.example.com/data", {
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return await response.json();
},
(error): FetchError => ({
type: "FetchError",
message: String(error),
}),
),
{
maxRetries: 3,
signal: controller.signal,
},
);
HTTP Request Recommendations
For HTTP requests, configure the retryable
option to only retry on
appropriate errors:
- DO retry: 429 (Too Many Requests), 503 (Service Unavailable), network errors
- DON'T retry: 4xx client errors (except 429), most 5xx server errors
Type Parameters
Type Parameter |
---|
T |
E |
Parameters
Parameter | Type |
---|---|
fn | () => Promise <Result <T , E >> |
options | RetryOptions <E > |
Returns
Promise
<Result
<T
,
| RetryAbortError
| RetryError
<E
>>>