Last active
August 29, 2015 14:15
-
-
Save alexdiliberto/bee170f6504f9a6a3cb4 to your computer and use it in GitHub Desktop.
How to timeout a long-running promise
This file contains hidden or 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
| /** | |
| 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