refactor: improve shutdown cleanup

This commit is contained in:
Carlos Valente
2026-03-13 22:52:18 +01:00
committed by Carlos Valente
parent 871a6b46c8
commit 4408bdb0d3
5 changed files with 135 additions and 30 deletions
+15
View File
@@ -0,0 +1,15 @@
/**
* Resolves or rejects with the provided promise, but fails if it does not settle within `timeoutMs`.
*/
export const withTimeout = <T>(promise: Promise<T>, timeoutMs: number): Promise<T> => {
let timer: NodeJS.Timeout | null = null;
const timeout = new Promise<T>((_, reject) => {
timer = setTimeout(() => reject(new Error('Operation timed out')), timeoutMs);
});
return Promise.race([promise, timeout]).finally(() => {
if (timer) {
clearTimeout(timer);
}
});
};