( promise: Promise<T>, timeoutMs: number, abortSignal?: AbortSignal, timeoutError?: Error )
| 120 | } |
| 121 | |
| 122 | async function waitForPromiseWithTimeout<T>( |
| 123 | promise: Promise<T>, |
| 124 | timeoutMs: number, |
| 125 | abortSignal?: AbortSignal, |
| 126 | timeoutError?: Error |
| 127 | ): Promise<T> { |
| 128 | if (abortSignal?.aborted) { |
| 129 | throw new Error("Operation aborted"); |
| 130 | } |
| 131 | |
| 132 | return await new Promise<T>((resolve, reject) => { |
| 133 | let settled = false; |
| 134 | |
| 135 | const cleanup = () => { |
| 136 | clearTimeout(timer); |
| 137 | abortSignal?.removeEventListener("abort", onAbort); |
| 138 | }; |
| 139 | |
| 140 | const finish = (handler: () => void) => { |
| 141 | if (settled) { |
| 142 | return; |
| 143 | } |
| 144 | settled = true; |
| 145 | cleanup(); |
| 146 | handler(); |
| 147 | }; |
| 148 | |
| 149 | const onAbort = () => { |
| 150 | finish(() => reject(new Error("Operation aborted"))); |
| 151 | }; |
| 152 | |
| 153 | const timer = setTimeout(() => { |
| 154 | finish(() => reject(timeoutError ?? new Error("Operation timed out"))); |
| 155 | }, timeoutMs); |
| 156 | |
| 157 | abortSignal?.addEventListener("abort", onAbort); |
| 158 | promise.then( |
| 159 | (value) => { |
| 160 | finish(() => resolve(value)); |
| 161 | }, |
| 162 | (error) => { |
| 163 | finish(() => reject(error instanceof Error ? error : new Error(String(error)))); |
| 164 | } |
| 165 | ); |
| 166 | }); |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * SSH Connection Pool |
no test coverage detected