Skip to content

Instantly share code, notes, and snippets.

@shameen
Created March 9, 2022 15:56
Show Gist options
  • Save shameen/17dbbba4b4e078de154c612c86ab0be1 to your computer and use it in GitHub Desktop.
Save shameen/17dbbba4b4e078de154c612c86ab0be1 to your computer and use it in GitHub Desktop.
Typescript promise with timeout
/** 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