Skip to content

Instantly share code, notes, and snippets.

Created August 13, 2022 02:04
What would you like to do?
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([
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