async function runWithLimit1(tasks, limit) {
const results = [];
let index = 0;
 
async function worker() {
while (index < tasks.length) {
const current = index;
index++;
console.log(`Worker starting task ${current + 1} at ${new Date().toLocaleTimeString()}`);
const res = await tasks[current]();
results[current] = res;
console.log(`Worker finished task ${current + 1} at ${new Date().toLocaleTimeString()}`);
}
}
 
const workers = Array(Math.min(limit, tasks.length))
.fill(null)
.map(worker);
 
await Promise.all(workers);
 
return results;
}
 
async function runWithLimit2(tasks, limit) {
if (!Array.isArray(tasks)) {
throw new TypeError('"tasks" should be an array');
}
 
if (!Number.isFinite(limit) || limit <= 0) {
throw new TypeError('"limit" should be positive');
}
 
const results = new Array(tasks.length);
let index = 0;
 
async function worker() {
while (index < tasks.length) {
const current = index++;
 
try {
results[current] = await tasks[current]();
} catch (e) {
results[current] = { error: e };
}
}
}
 
await Promise.all(
Array(Math.min(limit, tasks.length))
.fill(null)
.map(worker)
);
 
return results;
}
 
Click Run to execute JavaScript.
Code runs in an isolated environment.