| 5 | * the timeout duration. |
| 6 | */ |
| 7 | export function withTimeout(promise: DeferredPromise<any>, duration: number): void { |
| 8 | const timeout = setTimeout(() => { |
| 9 | // Prevent the timeout rejection if the Promise has already been settled. |
| 10 | // Rejecting a Promise multiple times is also a no-op, and it'd throw. |
| 11 | if (promise.state === 'pending') { |
| 12 | promise.reject(new Error(`DeferredPromise hasn't settled within ${duration}ms`)); |
| 13 | } |
| 14 | }, duration); |
| 15 | |
| 16 | const cancelTimeout = () => clearTimeout(timeout); |
| 17 | promise.then(cancelTimeout, cancelTimeout); |
| 18 | } |