Skip to content

Instantly share code, notes, and snippets.

@portothree
Last active June 23, 2022 12:09
Show Gist options
  • Select an option

  • Save portothree/9058f6d1d07940c71848e30c6957bdf4 to your computer and use it in GitHub Desktop.

Select an option

Save portothree/9058f6d1d07940c71848e30c6957bdf4 to your computer and use it in GitHub Desktop.
Timeout an Promise
function timeoutPromise(prom, time) {
let timer;
return Promise.race([
prom,
new Promise(
(_r, rej) =>
(timer = setTimeout(rej, time, new Error("Promise timed out")))
),
]).finally(() => clearTimeout(timer));
}
async function customPromise() {
await new Promise((res) => setTimeout(res, 500));
}
async function main() {
try {
await timeoutPromise(customProm(), 100);
} catch (error) {
console.log(error);
}
}
main(); // Error: Promise timed out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment