Async retry in TypeScript
Retries an async operation with backoff, typed on what it resolves to.
async function retry<T>(
fn: () => Promise<T>,
attempts = 3,
): Promise<T> {
let lastError: unknown;
for (let i = 0; i < attempts; i++) {
try {
return await fn();
} catch (err) {
lastError = err;
}
}
throw lastError;
}
Keywords and builtins used here
Promiseasyncawaitcatchforfunctionletreturnthrowtryunknown
The run, in numbers
- Lines
- 14
- Characters to type
- 218
- Tokens
- 72
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 41 seconds.
Step 5 of 5 in Timing & memory, step 18 of 19 in Classes & patterns.