Last active
August 3, 2021 03:13
-
-
Save danielcardeenas/374347ce9645f926eac24cc2d3298c7c to your computer and use it in GitHub Desktop.
Timeout Promise gracefully (Typed)
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
/** | |
* Puts a timeout to given promise. | |
* Will not error out. Instead will return given fallback value | |
* @param source | |
* @param time | |
* @param fallbackTo | |
* @returns | |
*/ | |
export function withTimeout<T>( | |
source: Promise<T>, | |
time: number, | |
fallbackTo: T, | |
): Promise<T> { | |
return Promise.race([ | |
source, | |
new Promise<T>((_r) => setTimeout(() => _r(fallbackTo), time)), | |
]); | |
} | |
// const someNumber = withTimeout(Promise.resolve(10), 500, 0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment