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