Last active
July 30, 2019 13:46
-
-
Save teroyks/b3e0454e0e9c1a1284ecee8e9686cd88 to your computer and use it in GitHub Desktop.
Javascript Timeout Wrapper
This file contains hidden or 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
const DEFAULT_TIMEOUT = 5000; | |
// rejects a promise if it doesn't finish within given time | |
const timeout = async (promise, ms = DEFAULT_TIMEOUT) => { | |
const rejectAfterTimeout = new Promise((resolve, reject) => setTimeout(reject, ms, 'timed out')) | |
return Promise.race([ | |
promise, | |
rejectAfterTimeout, | |
]) | |
} | |
// example functionality, to be wrapped in a timeout | |
const doSomething = async () => new Promise(resolve => setTimeout(resolve, 2000, 'OK')) | |
// wrap function, with timeout | |
const doSomethingTimeout = timeout(doSomething(), 1000) | |
doSomethingTimeout | |
.then(res => console.log(res)) | |
.catch(error => console.error(`ERROR: ${error}`)) | |
// call wrapper directly, with default timeout | |
timeout(doSomething()) | |
.then(res => console.log(`Default timeout: ${res}`)) | |
.catch(error => console.error(`ERROR with default timeout: ${error}`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment