feat: CancelableTask&Fallback

This commit is contained in:
手瓜一十雪 committed 2025-01-03 20:46:51 +08:00
1 parent 12301e633c
commit 5c91dbd819
3 files changed
+162 -30

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
type Handler<T> = () => T | Promise<T>;
export class Fallback<T> {
private handlers: Handler<T>[] = [];
add(handler: Handler<T>): this {
this.handlers.push(handler);
return this;
}
// 执行处理程序链
async run(): Promise<T> {
const errors: Error[] = [];
for (const handler of this.handlers) {
try {
const result = await handler();
if (result !== undefined) {
return result;
}
} catch (error) {
errors.push(error instanceof Error ? error : new Error(String(error)));
}
}
throw new AggregateError(errors, 'All handlers failed');
}
}