Reviewed-on: https://home.schmelczer.dev/git/git/andras/vault-link/pulls/190 Co-authored-by: Andras Schmelczer <andras@schmelczer.dev> Co-committed-by: Andras Schmelczer <andras@schmelczer.dev>
15 lines
486 B
TypeScript
15 lines
486 B
TypeScript
export async function withTimeout<T>(
|
|
promise: Promise<T>,
|
|
timeoutMs: number,
|
|
message: string
|
|
): Promise<T> {
|
|
let timeoutId: ReturnType<typeof setTimeout> | undefined = undefined;
|
|
const timeoutPromise = new Promise<never>((_resolve, reject) => {
|
|
timeoutId = setTimeout(() => {
|
|
reject(new Error(message));
|
|
}, timeoutMs);
|
|
});
|
|
return Promise.race([promise, timeoutPromise]).finally(() => {
|
|
clearTimeout(timeoutId);
|
|
});
|
|
}
|