Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created March 14, 2023 06:10
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 miguelmota/5b9f5ec5a3ae3b9dd89020733967c14c to your computer and use it in GitHub Desktop.
Save miguelmota/5b9f5ec5a3ae3b9dd89020733967c14c to your computer and use it in GitHub Desktop.
JavaScript promise timeout
class TimeoutError extends Error {}
export async function promiseTimeout<T> (promise: Promise<T>, timeout: number): Promise<T> {
return await new Promise(async (resolve, reject) => {
let timedout = false
const t = setTimeout(() => {
timedout = true
reject(new TimeoutError('timedout'))
}, timeout)
// make it a promise if it's not one
Promise.resolve(promise)
.then((result: any) => {
clearTimeout(t)
if (!timedout) {
resolve(result)
}
})
.catch((err: any) => {
clearTimeout(t)
if (!timedout) {
reject(err)
}
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment