Created
July 18, 2017 04:59
-
-
Save cromwellryan/12e6943d94a610b9279026a6b9f1925f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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