Skip to content

Instantly share code, notes, and snippets.

@nanha
Created November 15, 2011 05:00
Show Gist options
  • Save nanha/1366203 to your computer and use it in GitHub Desktop.
Save nanha/1366203 to your computer and use it in GitHub Desktop.
Async Programming Combo
function Combo(callback) {
this.callback = callback;
this.items = 0;
this.results = [];
}
Combo.prototype = {
add: function () {
var self = this,
id = this.items;
this.items++;
return function () {
self.check(id, arguments);
};
},
check: function (id, arguments) {
this.results[id] = Array.prototype.slice.call(arguments);
this.items--;
if (this.items == 0) {
this.callback.apply(this, this.results);
}
}
};
// Make a Combo object.
var both = new Combo(function (db_result, file_contents) {
// Do something
});
// Fire off the database query
people.find({name: "Tim", age: 27}, both.add());
// Fire off the file read
fs.readFile('famous_quotes.txt', both.add());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment