Skip to content

Instantly share code, notes, and snippets.

@teroyks
Last active July 30, 2019 13:46
Show Gist options
  • Save teroyks/b3e0454e0e9c1a1284ecee8e9686cd88 to your computer and use it in GitHub Desktop.
Save teroyks/b3e0454e0e9c1a1284ecee8e9686cd88 to your computer and use it in GitHub Desktop.
Javascript Timeout Wrapper
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