Skip to content

Instantly share code, notes, and snippets.

@luin
Created March 9, 2013 15:39
Show Gist options
  • Select an option

  • Save luin/5124550 to your computer and use it in GitHub Desktop.

Select an option

Save luin/5124550 to your computer and use it in GitHub Desktop.
a simple pool library for nodejs.
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