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