Created
February 17, 2014 17:29
-
-
Save ThomasBurleson/9055159 to your computer and use it in GitHub Desktop.
Example of using promise chains to delay and log messages. Uses Q Promises with setTimeout to create promise-based API delay() function.
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
/** | |
* Chain 2 Delay calls together in a non-nesting fashion | |
*/ | |
function myDelayedMessages() | |
{ | |
/** | |
* Delay function using Q promises and setTimeout() internally | |
*/ | |
var delay = function( duration ) | |
{ | |
var dfd = Q.defer(); | |
setTimeout(function () | |
{ | |
dfd.resolve( "Slept for "+time ); | |
}, time); | |
return dfd.promise; | |
}, | |
/** | |
* Function to wait <XX> msecs and log response to Console | |
*/ | |
waitAndLog = function( duration ) | |
{ | |
return function() | |
{ | |
return delay( duration ).then( function( msg ) | |
{ | |
console.log( msg ); | |
}); | |
}; | |
}; | |
waitAndLog(1000)().then( waitAndLog(2000) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Created as
tangible thoughts
to http://flippinawesome.org/2014/02/10/replacing-callbacks-with-es6-generators/#comment-15056