function promiseAllWithConcurrencyLimit(promises, limit) {
return new Promise((resolve, reject) => {
const results = [];
let currentIndex = 0;
let runningCount = 0;
// 定义一个函数来处理队列中的下一个 Promise
const runNext = () => {
if (currentIndex >= promises.length && runningCount === 0) {
// 所有 Promise 都已完成且没有正在运行的 Promise
resolve(results);
return;
}
// 只要还有 Promise 要处理且未达到并发限制,就继续运行
while (currentIndex < promises.length && runningCount < limit) {
const promise = promises[currentIndex++];
runningCount++;
// 运行 Promise 并将结果添加到 results 数组中
Promise.resolve(promise()).then(
(value) => {
results.push(value);
runningCount--;
runNext(); // 递归调用以处理下一个 Promise
},
(error) => {
reject(error); // 如果任何一个 Promise 失败,则拒绝整个 Promise
runningCount--; // 确保计数器减少,以便可以继续处理其他 Promise(尽管已经拒绝了)
}
);
}
};
// 开始处理队列
runNext();
});
}
// 使用示例
const tasks = [
() => new Promise((resolve) => setTimeout(() => resolve('Task 1'), 1000)),
() => new Promise((resolve) => setTimeout(() => resolve('Task 2'), 500)),
() => new Promise((resolve) => setTimeout(() => resolve('Task 3'), 300)),
// ... 更多任务
];
promiseAllWithConcurrencyLimit(tasks, 2).then(
(results) => console.log(results), // ['Task 2', 'Task 3', 'Task 1'](顺序可能不同,取决于执行时间)
(error) => console.error(error)
);
console