Created
October 2, 2015 13:59
-
-
Save fxposter/2f26a85392f328682c99 to your computer and use it in GitHub Desktop.
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
'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