Skip to content

Instantly share code, notes, and snippets.

@maatthc
Last active August 14, 2019 03:54
Show Gist options
  • Save maatthc/ecf0644253f4849c7fb3495bae3e1107 to your computer and use it in GitHub Desktop.
Save maatthc/ecf0644253f4849c7fb3495bae3e1107 to your computer and use it in GitHub Desktop.
Javascript Promises Timeout
//
// Javascript Promises Timeout
//
// A way to implement timeouts in jS promises using :
// - setTimeout():
// sets up a function to be called after a specified delay in milliseconds.
// - Promise.race():
// Creates a Promise that is resolved or rejected when any of the provided Promises are resolved or rejected.
//
// Run 'seq 10 | xargs -Iz node promise_timeout.js' on the command line to see the results flapping between 'Done' and 'TimeOut'
// (Tested on node v10.15.3 and Darwin Kernel Version 18.6.0)
const timeOut = async timeout => {
return new Promise(resolve => {
const wait = setTimeout(() => {
clearTimeout(wait)
resolve('TimeOut')
}, timeout)
})
}
const fakeService = async timeout => {
return new Promise(resolve => {
const wait = setTimeout(() => {
clearTimeout(wait)
resolve('Done')
}, timeout)
})
}
const init = async () => {
const result = await Promise.race([fakeService(501), timeOut(500)])
console.log(result)
}
init()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment