promise限并发的核心是并发池:维护运行中任务数组,用promise.race等待任一完成再入新任务;推荐p-limit库或手写concurrentpool类,避免分批all、定时器等无效方案。

用 Promise 限制最大并发数,核心是控制同时执行的异步任务数量,避免瞬间发起过多请求压垮服务或耗尽资源。最常用、最清晰的方式是使用 Promise 队列 + 并发池(concurrency pool),而不是靠 Promise.all 或 Promise.race 硬凑。
用 async/await + 并发池手动控制
定义一个固定大小的“执行槽位”,每次只允许指定数量的任务运行;新任务需等待有空槽才开始。
- 维护一个正在运行的任务数组(
running),长度即当前并发数 - 用
while循环 +await Promise.race(running)等待任一任务完成,腾出槽位 - 把新任务
push进去,并在结束后自动从running中移除
示例(限制最多 3 个并发):
async function limitConcurrency(tasks, limit = 3) {
const results = [];
const running = [];
for (const task of tasks) {
const promise = task().then(res => res).catch(err => err);
running.push(promise);
// 超过限制就等一个完成
if (running.length >= limit) {
await Promise.race(running);
// 移除已结束的 promise(注意:Promise.race 不会移除,需手动清理)
const doneIndex = running.findIndex(p => p.status === 'fulfilled' || p.status === 'rejected');
if (doneIndex !== -1) running.splice(doneIndex, 1);
}
}
// 等所有剩余任务完成
results.push(...await Promise.all(running));
return results;
}
⚠️ 注意:上面写法中直接检查 .status 不可行(Promise 实例没有该属性),真实项目建议用更健壮的实现——比如封装一个 Pool 类或用成熟库。
推荐:用 p-limit 库(轻量可靠)
p-limit 是专门解决这个问题的小而美工具,仅 2KB,无依赖。
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 安装:
npm install p-limit - 用法简洁直观:
import pLimit from 'p-limit';
const limit = pLimit(3); // 最大并发 3
const inputs = [1, 2, 3, 4, 5].map(x => () => fetch(`/api/item/${x}`));
// 所有任务入队,自动排队执行
const results = await Promise.all(inputs.map(input => limit(input)));
它内部用队列 + 可重用的 Promise 槽位管理,支持取消、错误传播,且不污染原始函数。
进阶:手写通用并发池类(适合学习/定制)
如果想深入理解或需要扩展功能(如优先级、超时、重试),可自己实现一个 ConcurrentPool:
- 用
queue存待执行函数,用active记当前运行数 - 每次调用
add(fn)时:若active 就立即执行;否则推入队列 - 每个任务结束时调用
next(),从队列取下一个执行
关键逻辑片段:
class ConcurrentPool {
constructor(limit) {
this.limit = limit;
this.active = 0;
this.queue = [];
}
add(fn) {
return new Promise((resolve, reject) => {
this.queue.push({ fn, resolve, reject });
this.next();
});
}
next() {
if (this.active >= this.limit || this.queue.length === 0) return;
this.active++;
const { fn, resolve, reject } = this.queue.shift();
fn().then(resolve).catch(reject).finally(() => {
this.active--;
this.next(); // 触发下一个
});
}
}
// 使用
const pool = new ConcurrentPool(3);
const promises = urls.map(url => pool.add(() => fetch(url)));
const results = await Promise.all(promises);
不推荐的做法(容易踩坑)
-
用
Promise.all分批 +slice:虽然能分段,但无法动态调度,前一批全完才能启下一批,实际并发率低 -
用
setTimeout或setInterval控制节奏:时间不可控,网络延迟会让并发数漂移 -
在
fetch前加await delay:只是错峰,不是真正限并发,仍可能堆积大量 pending 请求
真正有效的限并发,必须基于“任务完成反馈”来释放资源,而不是靠时间或静态分组。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










