Created
August 13, 2022 02:04
-
-
Save Poxios/8bc45c7b02fe3e82aa0b0a52b0edaa47 to your computer and use it in GitHub Desktop.
Throw Error on Timeout (Typescript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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