JSFiddle - React, Tailwind, and code Playground
JavaScript
function makeWork(v) {
return { value: v, promise: new Promise(resolve => setTimeout(() => resolve(v), v)) };
}
async function* gen(tasks, n) {
// Start n work
const parallel = tasks.slice(0, n).map(v => makeWork(v));
tasks = tasks.slice(n);
while (parallel.length != 0) {
const value = await Promise.race(parallel.map(t => t.promise));
parallel.splice(parallel.findIndex(t => t.value == value), 1);
yield value;
// Add 1 more work
if (tasks.length != 0) {
parallel.push(makeWork(tasks.shift()));
}
}
}
const tasks = [100, 50, 20, 200, 150, 1, 2, 5, 21, 120, 130, 15];
(async () => {
for await (const a of gen(tasks, 5)) {
console.log(a);
}
})();