Skip to content

Instantly share code, notes, and snippets.

@connorads
Created September 25, 2020 10:47
Show Gist options
  • Save connorads/d7794bc5864142208e59158c8bee3d76 to your computer and use it in GitHub Desktop.
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)
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;
}
@connorads
Copy link
Author

TODO: Fix timeout clearing if promise() is rejected?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment