Created
March 14, 2023 06:10
-
-
Save miguelmota/5b9f5ec5a3ae3b9dd89020733967c14c to your computer and use it in GitHub Desktop.
JavaScript promise timeout
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
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