Skip to content

Instantly share code, notes, and snippets.

@ChristianIvicevic
Created March 12, 2021 11:48
Show Gist options
  • Save ChristianIvicevic/d715482fd20b681765b0a4f6c7c0ee4e to your computer and use it in GitHub Desktop.
Save ChristianIvicevic/d715482fd20b681765b0a4f6c7c0ee4e to your computer and use it in GitHub Desktop.
/**
* Rejects any promise after the specified amount of time (in ms). Useful for
* timing out long-running operations that didn't resolve in time.
* @param promise Promise to race against.
* @param timeout Time in ms to wait until rejecting the promise unless it
* resolved in time.
* @return A new promise that either behaves like the original promise or
* rejects after the specified amount of time.
*/
export const racePromise = async <T>(promise: Promise<T>, timeout: number) => {
let timeoutId: number;
return Promise.race([
promise,
new Promise<T>((_, reject) => {
timeoutId = window.setTimeout(reject, timeout);
}),
]).finally(() => {
clearTimeout(timeoutId);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment