Created
March 9, 2022 15:56
-
-
Save shameen/17dbbba4b4e078de154c612c86ab0be1 to your computer and use it in GitHub Desktop.
Typescript promise with timeout
This file contains hidden or 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
/** Await a promise, or reject after X milliseconds */ | |
const asyncWithTimeout = async <T>(promise: Promise<T>, milliseconds = 10000): Promise<T> => { | |
//Promise that rejects after X milliseconds | |
const timeoutPromise = new Promise((_, reject) => | |
setTimeout(() => reject(`timed out after ${milliseconds} milliseconds`), milliseconds), | |
); | |
return await Promise.race([promise, timeoutPromise]) | |
.then((result) => result as T) | |
.catch((e) => { | |
throw Error(e); | |
}); | |
} | |
export { | |
asyncWithTimeout | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment