Created
November 15, 2011 05:00
-
-
Save nanha/1366203 to your computer and use it in GitHub Desktop.
Async Programming Combo
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 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