forked from Shared/esg
initial commit
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Races an async operation against a timeout.
|
||||
* Throws a distinguishable error for BaseProvider normalization.
|
||||
*/
|
||||
export async function withTimeout<T>(
|
||||
promise: Promise<T>,
|
||||
timeoutMs: number,
|
||||
label = 'Operation',
|
||||
): Promise<T> {
|
||||
let timeoutHandle: NodeJS.Timeout;
|
||||
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
const error = new Error(`${label} timed out after ${timeoutMs}ms`);
|
||||
(error as NodeJS.ErrnoException).code = 'ETIMEDOUT';
|
||||
reject(error);
|
||||
}, timeoutMs);
|
||||
});
|
||||
|
||||
try {
|
||||
return await Promise.race([promise, timeoutPromise]);
|
||||
} finally {
|
||||
clearTimeout(timeoutHandle!);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user