JavaScript并发控制通过Promise+队列+计数器实现,用固定槽位限制同时执行任务数(如3个),新任务入队等待空闲,running计数器跟踪运行中任务,完成即释放槽位并调度下一个。

JavaScript 并发控制的核心是限制同时执行的异步任务数量,避免资源耗尽或接口限流报错。不靠轮询、不靠 setTimeout 模拟,而是用 Promise 配合队列 + 计数器来稳稳调度。
本质是维护一个最大并发数(比如 3),只允许最多 3 个 Promise 同时处于 pending 状态。新任务来了不立刻执行,而是进队列等待空闲槽位。
下面是一个轻量实用的实现(ES6 Class):
class ConcurrencyController {
constructor(max) {
this.max = max
this.running = 0
this.taskQueue = []
}
<p>push(fn) {
return new Promise((resolve, reject) => {
this.taskQueue.push({ fn, resolve, reject })
this.#run()
})
}</p><h1>run() {</h1><pre class='brush:php;toolbar:false;'>if (this.running >= this.max || this.taskQueue.length === 0) return
this.running++
const { fn, resolve, reject } = this.taskQueue.shift()
fn().then(resolve).catch(reject).finally(() => {
this.running--
this.#run() // 尝试调度下一个
})} }
使用示例:同时最多请求 2 个接口
立即学习“Java免费学习笔记(深入)”;
const controller = new ConcurrencyController(2) <p>const tasks = urls.map(url => () => fetch(url).then(r => r.json()) )</p><p>Promise.all(tasks.map(task => controller.push(task))) .then(results => console.log(results))</p>
原生 Promise 不支持取消,但你可以加一层包装:
不过多数业务场景只需基础调度——保证不超并发、结果顺序无关、失败不影响其他任务即可。
基本上就这些。关键不是写多 fancy 的代码,而是想清楚:谁排队、谁占位、谁释放、谁接替。
以上就是如何实现javascript并发控制_多个异步任务怎样调度?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号