Skip to content

Instantly share code, notes, and snippets.

@cromwellryan
Created July 18, 2017 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cromwellryan/12e6943d94a610b9279026a6b9f1925f to your computer and use it in GitHub Desktop.
Save cromwellryan/12e6943d94a610b9279026a6b9f1925f to your computer and use it in GitHub Desktop.
/* npm install promise */
const Promise = require('promise');
function within(time) {
return new Promise(function (fulfill) {
setTimeout(fulfill, time);
});
}
function timeout(promise, milliseconds) {
return Promise.race([promise, within(milliseconds).then(function () {
throw new Error(`Operation timed out after ${milliseconds}ms`);
})]);
}
function slowNetworkRequest() {
return new Promise( (fulfill) => {
const data = { name: 'Ryan Cromwell' };
setTimeout( () => { fulfill(data) }, 5000 );
});
}
/* Passes because we wait 5.5 seconds */
timeout(slowNetworkRequest(), 5500)
.then( data => console.log(`Name: ${data.name}`) )
.catch( err => console.log(err) );
/* Fails because we only wait 2.5 seconds */
timeout(slowNetworkRequest(), 2500)
.then( data => console.log(`Name: ${data.name}`) )
.catch( err => console.log(err) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment