(
promise: Promise<T>,
timeoutMs: number,
timeoutMessage: string = `Operation timed out after ${timeoutMs}ms`,
)
| 51 | * @returns A promise that resolves with the result of the original promise or rejects with a timeout error |
| 52 | */ |
| 53 | export async function withTimeout<T>( |
| 54 | promise: Promise<T>, |
| 55 | timeoutMs: number, |
| 56 | timeoutMessage: string = `Operation timed out after ${timeoutMs}ms`, |
| 57 | ): Promise<T> { |
| 58 | let timeoutId: NodeJS.Timeout |
| 59 | |
| 60 | const timeoutPromise = new Promise<never>((_, reject) => { |
| 61 | timeoutId = setTimeout(() => { |
| 62 | reject(new Error(timeoutMessage)) |
| 63 | }, timeoutMs) |
| 64 | }) |
| 65 | |
| 66 | return Promise.race([ |
| 67 | promise.then((result) => { |
| 68 | clearTimeout(timeoutId) |
| 69 | return result |
| 70 | }), |
| 71 | timeoutPromise, |
| 72 | ]) |
| 73 | } |
no test coverage detected