Created
September 14, 2017 10:14
-
-
Save odesskij/56ca17de17db31315e4c413f317b787e to your computer and use it in GitHub Desktop.
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 manager(tasks, worker, concurrency) { | |
const res = []; | |
function assign(w) { | |
return new Promise((resolve) => { | |
const t = tasks.shift(); | |
if (t === undefined) { | |
return resolve(); | |
} | |
console.log('assign %s', t); | |
return w(t).then((r) => res.push(r)) | |
.then(() => assign(w)) | |
.then(resolve); | |
}); | |
} | |
return Promise.all(Array.from(new Array(concurrency)).map(() => assign(worker))) | |
.then(() => res) | |
} | |
function worker(t) { | |
return new Promise((r) => setTimeout(r, Math.random() * 1000)) | |
.then(() => `r_${t}`) | |
} | |
// Test | |
manager( | |
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], | |
worker, | |
3 | |
).then((r) => console.log(r)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refactored
Usage
Output