(promise: Promise<T>, ms: number, onTimeoutError?: () => Error)
| 5 | * @param onTimeoutError 可选:自定义超时错误构造器;默认抛 Error("operation timed out") |
| 6 | */ |
| 7 | export function withTimeout<T>(promise: Promise<T>, ms: number, onTimeoutError?: () => Error): Promise<T> { |
| 8 | let timer: ReturnType<typeof setTimeout>; |
| 9 | const timeoutPromise = new Promise<never>((_, reject) => { |
| 10 | timer = setTimeout(() => { |
| 11 | reject(onTimeoutError ? onTimeoutError() : new Error("operation timed out")); |
| 12 | }, ms); |
| 13 | }); |
| 14 | return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timer)); |
| 15 | } |
no outgoing calls
no test coverage detected