Last active
January 26, 2021 08:09
-
-
Save iOliverNguyen/9617218a57f568f98d5e4e059aeb734f to your computer and use it in GitHub Desktop.
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
// execute function(s) with a limit timeout, throws error if the function(s) | |
// do not complete within the given time | |
export function execWithTimeout(timeout, ...promises) { | |
let timeoutId; | |
const countDown = new Promise((_, reject) => { | |
timeoutId = setTimeout(reject, timeout, new Error('timed out')); | |
}); | |
return Promise.race([countDown, ...promises]).then((result) => { | |
clearTimeout(timeoutId); | |
return result; | |
}); | |
} | |
// example usage | |
async function doSomething() { | |
const resp = await fetch('https://registry.npmjs.org/react') | |
const body = await resp.json() | |
console.log(body.name) | |
} | |
execWithTimeout(1000, doSomething()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment