forked from angular/web-codegen-scorer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeout.ts
More file actions
32 lines (29 loc) · 915 Bytes
/
timeout.ts
File metadata and controls
32 lines (29 loc) · 915 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
export class TimeoutError extends Error {}
/**
* @throws {TimeoutError} thrown when the action did not complete within the timeout.
*/
export async function callWithTimeout<T>(
description: string,
fn: (signal: AbortSignal) => Promise<T>,
timeoutInMin: number,
): Promise<T> {
const abortController = new AbortController();
let timeoutID: NodeJS.Timeout | null = null;
const timeoutPromise = new Promise<never>((_resolve, reject) => {
timeoutID = setTimeout(
() => {
reject(new TimeoutError(`Timeout exceeded for action: ${description}`));
// Trigger abort signal to cleanup/kill e.g. processes behind a timeout.
abortController.abort();
},
1000 * 60 * timeoutInMin,
);
});
try {
return await Promise.race([fn(abortController.signal), timeoutPromise]);
} finally {
if (timeoutID !== null) {
clearTimeout(timeoutID);
}
}
}