( operation: Promise<T>, timeoutMs: number, errorMsg: string, onTimeout?: () => void )
| 7 | * @param onTimeout Optional callback to invoke when timeout occurs |
| 8 | */ |
| 9 | export async function withTimeout<T>( |
| 10 | operation: Promise<T>, |
| 11 | timeoutMs: number, |
| 12 | errorMsg: string, |
| 13 | onTimeout?: () => void |
| 14 | ): Promise<T> { |
| 15 | let timeoutId: ReturnType<typeof setTimeout> | undefined; |
| 16 | |
| 17 | const timeoutPromise = new Promise<never>((_, reject) => { |
| 18 | timeoutId = setTimeout(() => { |
| 19 | onTimeout?.(); |
| 20 | reject(new Error(errorMsg)); |
| 21 | }, timeoutMs); |
| 22 | }); |
| 23 | |
| 24 | try { |
| 25 | return await Promise.race([operation, timeoutPromise]); |
| 26 | } finally { |
| 27 | if (timeoutId !== undefined) { |
| 28 | clearTimeout(timeoutId); |
| 29 | } |
| 30 | } |
| 31 | } |
no test coverage detected