// // 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()