实现说明
除了函数 retryAsync,文件里再无其他定义。
循环只出现在 while (attempt < options.attempts),它的每次迭代处理一个元素。await 标出每个异步边界——没有 fire-and-forget。
使用要点
- 调用方只需要
retryAsync——其余都是内部实现。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 retryAsync。
核心语句
await new Promise<void>((resolve) => setTimeout(resolve, options.delayMs * attempt));
const shouldRetry = options.isRetryable ?? (() => true);
return await task();
代码示例
export interface RetryOptions {
attempts: number;
delayMs: number;
isRetryable?: (error: unknown) => boolean;
}
export async function retryAsync<T>(
task: () => Promise<T>,
options: RetryOptions,
): Promise<T> {
const shouldRetry = options.isRetryable ?? (() => true);
let attempt = 0;
let lastError: unknown;
while (attempt < options.attempts) {
attempt++;
try {
return await task();
} catch (error) {
lastError = error;
if (attempt >= options.attempts || !shouldRetry(error)) break;
await new Promise<void>((resolve) => setTimeout(resolve, options.delayMs * attempt));
}
}
throw lastError;
}