Skip to content

Instantly share code, notes, and snippets.

@odesskij
Created September 14, 2017 10:14
Show Gist options
  • Save odesskij/56ca17de17db31315e4c413f317b787e to your computer and use it in GitHub Desktop.
Save odesskij/56ca17de17db31315e4c413f317b787e to your computer and use it in GitHub Desktop.
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));
@tomfun
Copy link

tomfun commented Sep 14, 2017

My code is the same, but keep order of results, so it more close with bluebird.map

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment