Skip to content

Instantly share code, notes, and snippets.

@danielcardeenas
Last active August 3, 2021 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielcardeenas/374347ce9645f926eac24cc2d3298c7c to your computer and use it in GitHub Desktop.
Save danielcardeenas/374347ce9645f926eac24cc2d3298c7c to your computer and use it in GitHub Desktop.
Timeout Promise gracefully (Typed)
/**
* 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