Created
December 27, 2012 23:22
-
-
Save criso/4393089 to your computer and use it in GitHub Desktop.
Batch js calls
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 randomTime() { | |
return Math.floor(Math.random() * 100) + 100; | |
} | |
function asyncFoo(_callback) { | |
var err = false; | |
setTimeout(function() { | |
_callback({foo: "I am foo"}, err); | |
}, randomTime()); | |
} | |
function asyncBar(_callback) { | |
var err = false; | |
setTimeout(function() { | |
_callback({bar: "I am bar"}, err); | |
}, randomTime()); | |
} | |
function done(results) { | |
console.log("I am DONE", results); | |
} | |
function main() { | |
console.log("starting"); | |
var next = batch(done); | |
asyncBar(next()); | |
asyncFoo(next()); | |
} | |
main(); |
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 batch(done) { | |
var pending = 0; | |
var finished = false; | |
var results = {}; | |
return function(){ | |
++pending; | |
return function(response, err){ | |
if (finished) return; | |
if (err) { | |
finished = true; | |
return done(err); | |
} | |
for (var key in response) { | |
results[key] = response[key]; | |
} | |
console.log("pending calls: ", pending); | |
--pending || done(results); | |
}; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment