Concurrency Limit Pool
NodeJS
Hard
4 views
Problem Description
Run tasks with max 2 concurrency and print completion order.
Output Format
Print JSON array.
Constraints
Implement a simple promise pool.
Official Solution
function task(name, ms) {
return new Promise((r) => setTimeout(() => r(name), ms));
}
async function runPool(items, limit) {
const out = [];
let i = 0;
const workers = Array.from({ length: limit }, async () => {
while (i < items.length) {
const idx = i++;
out[idx] = await items[idx]();
}
});
await Promise.all(workers);
return out;
}
(async () => {
const jobs = [
() => task('a', 30),
() => task('b', 10),
() => task('c', 20),
() => task('d', 5)
];
const res = await runPool(jobs, 2);
console.log(JSON.stringify(res));
})();
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!