Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* 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