Skip to content

Instantly share code, notes, and snippets.

@criso
Created Dec 27, 2012
Embed
What would you like to do?
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