Created
September 25, 2020 10:47
-
-
Save connorads/d7794bc5864142208e59158c8bee3d76 to your computer and use it in GitHub Desktop.
Wrapping a promise with a timeout in Typescript (adapted from https://bit.ly/3j1fmli)
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 class TimeoutError extends Error { | |
constructor(message: string) { | |
super(message); | |
this.name = "TimeoutError"; | |
} | |
} | |
export const promiseWithTimeout = <T>({ | |
ms, | |
promise, | |
cancelPromise, | |
timeoutErrorMessage = `Timed out after ${ms}ms` | |
}: PromiseWithTimeoutOptions<T>) => { | |
let timeoutHandle: ReturnType<typeof setTimeout>; | |
const timeoutPromise = new Promise<never>((_, reject) => { | |
timeoutHandle = setTimeout(() => { | |
if (cancelPromise) cancelPromise(); | |
reject(new TimeoutError(timeoutErrorMessage)); | |
}, ms); | |
}); | |
return Promise.race([promise(), timeoutPromise]).then(result => { | |
clearTimeout(timeoutHandle); | |
return result; | |
}); | |
}; | |
interface PromiseWithTimeoutOptions<T> { | |
ms: number; | |
promise: () => Promise<T>; | |
cancelPromise?: () => void; | |
timeoutErrorMessage?: string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO: Fix timeout clearing if
promise()
is rejected?