Skip to content

Instantly share code, notes, and snippets.

@criso
Created December 27, 2012 23:22
Show Gist options
  • Save criso/4393089 to your computer and use it in GitHub Desktop.
Save criso/4393089 to your computer and use it in GitHub Desktop.
Batch js calls
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();
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