// Напиши функцию runWithLimit, которая:
// Принимает массив асинхронных задач и лимит параллельных выполнений
// Выполняет задачи с указанным лимитом
// Возвращает массив результатов в правильном порядке
const promisePool = async (tasksPool, limit) => {
const result = [];
let index = 0;
const runTask = async () => {
if (index >= tasksPool.length) return;
const idx = index;
index += 1;
const res = await tasksPool[idx]();
result[idx] = res;
await runTask();
};
await Promise.all(Array.from({ length: Math.min(limit, tasksPool.length) }, runTask));
return result;
};
const tasks = [
() => new Promise(res => setTimeout(() => res('A done'), 2000)),
() => new Promise(res => setTimeout(() => res('B done'), 1500)),
() => new Promise(res => setTimeout(() => res('C done'), 1000)),
() => new Promise(res => setTimeout(() => res('D done'), 500)),
() => new Promise(res => setTimeout(() => res('A done'), 5000)),
() => new Promise(res => setTimeout(() => res('B done'), 4500)),
() => new Promise(res => setTimeout(() => res('C done'), 3000)),
() => new Promise(res => setTimeout(() => res('D done'), 2500)),
];
promisePool(tasks, 2).then(results => console.log('All results:', results));
Click Run to execute JavaScript.
Code runs in an isolated environment.
Code runs in an isolated environment.