Files
esg/src/common/helpers/timeout.helper.ts
T

32 lines
1.0 KiB
TypeScript

/**
* Runs an async operation with a per-attempt timeout.
*
* The operation receives an AbortSignal so HTTP clients can stop the actual
* in-flight request when the timeout wins. A timeout without cancellation
* would only stop awaiting the promise and could leave sockets/slots busy.
*/
export async function withTimeout<T>(
operation: (signal: AbortSignal) => Promise<T>,
timeoutMs: number,
label = 'Operation',
): Promise<T> {
const controller = new AbortController();
let timeoutHandle: NodeJS.Timeout;
const operationPromise = Promise.resolve().then(() => operation(controller.signal));
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutHandle = setTimeout(() => {
const error = new Error(`${label} timed out after ${timeoutMs}ms`);
(error as NodeJS.ErrnoException).code = 'ETIMEDOUT';
controller.abort();
reject(error);
}, timeoutMs);
});
try {
return await Promise.race([operationPromise, timeoutPromise]);
} finally {
clearTimeout(timeoutHandle!);
}
}