Created
March 12, 2021 11:48
-
-
Save ChristianIvicevic/d715482fd20b681765b0a4f6c7c0ee4e to your computer and use it in GitHub Desktop.
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
/** | |
* 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