15 lines
736 B
TypeScript
15 lines
736 B
TypeScript
export class RequestTimeoutError extends Error {
|
|
constructor() { super('请求超时'); this.name = 'RequestTimeoutError'; }
|
|
}
|
|
|
|
/** 限制整个请求(包括读取响应正文)的等待时间,并终止底层网络连接。 */
|
|
export async function withRequestDeadline<T>(operation: (signal: AbortSignal) => Promise<T>, timeoutMs: number): Promise<T> {
|
|
const controller = new AbortController();
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
const expired = new Promise<never>((_, reject) => {
|
|
timer = setTimeout(() => { reject(new RequestTimeoutError()); controller.abort(); }, timeoutMs);
|
|
});
|
|
try { return await Promise.race([operation(controller.signal), expired]); }
|
|
finally { clearTimeout(timer); }
|
|
}
|