通过维护一个固定大小的并发池和任务队列来实现,核心逻辑是当有任务进入时检查当前活跃任务数是否达到上限,若未达上限则立即执行并增加计数,否则将任务推入等待队列。当任意一个任务完成时,从队列中取出下一个任务继续执行,直到队列为空且无活跃任务为止。

如何初始化并发限制器并注册新任务
初始化时需要传入最大并发数 limit 和一个可选的 onError 回调。注册任务时,先判断当前正在运行的任务数量是否小于 limit,如果满足条件,则直接启动该任务;如果不满足,则将任务加入内部队列等待。

class ConcurrencyLimiter {
constructor(limit, onError) {
this.limit = limit;
this.activeCount = 0;
this.queue = [];
this.onError = onError || ((err) => console.error(err));
}
addTask(taskFn) {
return new Promise((resolve, reject) => {
const wrappedTask = async () => {
try {
const result = await taskFn();
resolve(result);
} catch (err) {
if (this.onError) this.onError(err);
reject(err);
} finally {
this.activeCount--;
this.processQueue();
}
};
if (this.activeCount < this.limit) {
this.activeCount++;
wrappedTask();
} else {
this.queue.push(wrappedTask);
}
});
}
processQueue() {
while (this.queue.length > 0 && this.activeCount < this.limit) {
const nextTask = this.queue.shift();
this.activeCount++;
nextTask();
}
}
}
如何处理任务完成后的队列调度
每个任务在结束前(无论成功或失败)都会触发 finally 块,其中减少活跃计数并调用 processQueue。该方法会循环检查队列,只要还有任务且有空闲槽位,就取出任务并立即执行,从而保证并发度始终维持在设定值附近。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。
立即学习“Java免费学习笔记(深入)”;

// 使用示例
const limiter = new ConcurrencyLimiter(3);
const tasks = [1, 2, 3, 4, 5].map(id => () =>
fetch(`/api/data/${id}`).then(r => r.json())
);
Promise.all(tasks.map(t => limiter.addTask(t)))
.then(results => console.log('All done', results))
.catch(err => console.error('Failed', err));
当所有任务都完成后如何确认状态
由于 addTask 返回的是 Promise,外部可以通过 Promise.all 收集所有任务的最终结果。只有当队列清空且没有活跃任务时,所有关联的 Promise 才会 settle,此时可以安全地认为整个批处理已完成。

















