Created
November 16, 2013 09:23
-
-
Save nsonnad/7498027 to your computer and use it in GitHub Desktop.
control flow library, from mixu's node book
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
function series (callbacks, last) { | |
var results = []; | |
function next () { | |
var callback = callbacks.shift(); | |
if(callback) { | |
callback(function() { | |
results.push(Array.prototype.slice.call(arguments)); | |
next(); | |
}); | |
} else { | |
last(results); | |
} | |
} | |
next(); | |
} | |
// Example task | |
function async (arg, callback) { | |
var delay = Math.floor(Math.random() * 5 + 1) * 100; | |
console.log('async with \''+arg+'\', return in '+delay+' ms'); | |
setTimeout(function() { callback(arg * 2); }, delay); | |
} | |
function final(results) { console.log('Done', results); } | |
series([ | |
function(next) { async(1, next); }, | |
function(next) { async(2, next); }, | |
function(next) { async(3, next); }, | |
function(next) { async(4, next); }, | |
function(next) { async(5, next); }, | |
function(next) { async(6, next); } | |
], final); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment