Skip to content

Instantly share code, notes, and snippets.

@Poxios
Created August 13, 2022 02:04
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Poxios/8bc45c7b02fe3e82aa0b0a52b0edaa47 to your computer and use it in GitHub Desktop.
Throw Error on Timeout (Typescript)
export async function timeout<T>(promise: Promise<T>, ms: number): Promise<T> {
let timer: NodeJS.Timeout;
const res = await Promise.race([
promise,
new Promise<'timeout'>(resolve => {
timer = setTimeout(() => resolve('timeout'), ms);
})
] as const).finally(() => clearTimeout(timer));
if (res === 'timeout') {
throw new Error(`${ms}ms timeout`);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment