Skip to content

Instantly share code, notes, and snippets.

@alexdiliberto
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save alexdiliberto/bee170f6504f9a6a3cb4 to your computer and use it in GitHub Desktop.

Select an option

Save alexdiliberto/bee170f6504f9a6a3cb4 to your computer and use it in GitHub Desktop.
How to timeout a long-running promise
/**
Credit: Kyle Simpson
https://github.com/getify/You-Dont-Know-JS/blob/master/async%20&%20performance/ch3.md#never-calling-the-callback
*/
// A utility for timing out a Promise
function timeoutPromise(delay) {
return new Promise( function(resolve,reject) {
setTimeout( function() {
reject( "Timeout!" );
}, delay );
} );
}
// setup a timeout for `foo()`
Promise.race( [
foo(), // attempt `foo()`
timeoutPromise( 3000 ) // give it 3 seconds
] )
.then(
function(){
// `foo(..)` fulfilled in time!
},
function(err){
// either `foo()` rejected, or it just
// didn't finish in time, so inspect
// `err` to know which
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment