Created
March 9, 2013 15:39
-
-
Save luin/5124550 to your computer and use it in GitHub Desktop.
a simple pool library for nodejs.
This file contains hidden or 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
| var Pool = function (poolSize, taskHandler) { | |
| this.poolSize = poolSize; | |
| this.taskHandler = taskHandler; | |
| this.free = poolSize; | |
| this.offlineTasks = []; | |
| }; | |
| Pool.prototype.check = function () { | |
| if (this.offlineTasks.length > 0 && this.free > 0) { | |
| var task = this.offlineTasks.shift(); | |
| var data = task[0]; | |
| var callback = task[1]; | |
| this.free += 1; | |
| this.taskHandler(data, function (err, result) { | |
| this.free -= 1; | |
| this.check(); | |
| if (typeof callback === 'function') { | |
| callback(err, result); | |
| } | |
| }); | |
| } | |
| }; | |
| Pool.prototype.push = function (data, callback) { | |
| this.offlineTasks.push([data, callback]); | |
| this.check(); | |
| return this; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment