Skip to content

Instantly share code, notes, and snippets.

@fxposter
Created October 2, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fxposter/2f26a85392f328682c99 to your computer and use it in GitHub Desktop.
Save fxposter/2f26a85392f328682c99 to your computer and use it in GitHub Desktop.
'use strict';
class Executor {
constructor(maxTasksInParallel) {
this._maxTasksInParallel = maxTasksInParallel;
this._currentTasks = 0;
this._queue = [];
}
start(task) {
if (this._currentTasks < this._maxTasksInParallel) {
this._currentTasks++;
return task().then(this._taskFinished.bind(this), this._taskFinished.bind(this));
} else {
return new Promise((resolve, reject) => {
this._queue.push([task, resolve, reject]);
});
}
}
_taskFinished(result) {
if (this._queue.length) {
var next = this._queue.pop();
var task = next[0]
var resolve = next[1];
var reject = next[2];
task().then(this._taskFinished.bind(this), this._taskFinished.bind(this)).then(resolve, reject);
} else {
this._currentTasks--;
}
return result;
}
}
var e = new Executor(5);
for(let i = 0; i < 10; ++i) {
e.start(function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log(i);
resolve(i);
}, i*100);
})
}).then(function(r) {
console.log(r);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment