JavaScript并发控制:从Promise到队列系统

一、并发控制基础概念

为什么需要并发控制?

当应用同时处理多个异步操作时(如API请求、文件操作等),无限制的并发会导致:

  • 资源耗尽(内存、CPU、网络带宽)
  • 服务端拒绝服务(HTTP 429错误)
  • 级联故障(雪崩效应)
graph LR A[大量并发请求] --> B[资源耗尽] B --> C[服务崩溃] C --> D[级联故障]

JavaScript并发模型

JavaScript使用事件循环(Event Loop)处理并发,但Node.js和浏览器环境有所不同:

环境 并发模型 特点
浏览器 单线程事件循环 每个标签页独立线程
Node.js 多线程+事件循环 Worker Threads处理CPU密集型任务

二、基础并发控制实现

1. Promise.all的并发限制

原生Promise.all无法控制并发数,我们可以实现一个简单的控制版本:

javascript 复制代码
async function promiseAllLimited(tasks, limit) {
    const results = [];
    const executing = new Set();

    for (const task of tasks) {
        // 等待并发数低于限制
        if (executing.size >= limit) {
            await Promise.race(executing);
        }

        const p = task().then(res => {
            executing.delete(p);
            return res;
        });

        executing.add(p);
        results.push(p);
    }

    return Promise.all(results);
}

// 使用示例
const tasks = [];

for (let i = 0; i < 50; i++) {
    tasks.push(() => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log(i);
                resolve(i);
            }, 1000 * Math.floor(10 * Math.random()));
        })
    });
}

promiseAllLimited(tasks, 5); // 最大并发5个

2. 基础队列并发控制模型

基础队列并发控制模型,具体的控制队列可以根据自身业务进行扩展,例如添加超时控制,性能监测,任务优先级控制等等

javascript 复制代码
class TaskQueue {
    constructor(concurrency) {
        this.concurrency = concurrency;
        this.running = 0;
        this.queue = [];
    }

    push(task) {
        this.queue.push(task);
        this.next();
    }

    next() {
        while (this.running < this.concurrency && this.queue.length) {
            const task = this.queue.shift();
            task().finally(() => {
                this.running--;
                this.next();
            });
            this.running++;
        }
    }
}

// 使用示例
const queue = new TaskQueue(3);

for (let i = 0; i < 10; i++) {
    queue.push(() => new Promise(resolve => {
        console.log(`任务 ${i} 开始`);
        setTimeout(() => {
            console.log(`任务 ${i} 完成`);
            resolve();
        }, Math.random() * 2000);
    }));
}

结语

如果你喜欢本教程,记得点赞+收藏!关注我获取更多JavaScript开发干货。

相关推荐
JavaGuide7 小时前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
zhanlang02177 小时前
HTML 零基础入门到企业实战全套教程【第九章 9.3】移动端 HTML 基础适配入门
前端·html
用户69371750013847 小时前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github
skywalk81637 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
彭亚川Allen8 小时前
从零手搓 RAG:用 Elasticsearch 存储与检索向量
前端·后端·面试
jerrywus8 小时前
15 个可以直接安装的 AI Agent Skills:按场景挑
前端·agent·claude
涛涛ing8 小时前
用了三年微前端,我们终于把它拆成了单体应用
前端
去伪存真9 小时前
《最终版》《打死不改版》全传一遍?RAG 系统文件去重实战
前端
anyup9 小时前
【全端支持】 uni-app x 专用请求库:axios 写法,多实例、拦截器、可中断、上传下载
前端·uni-app·unix
费曼学习法9 小时前
6 个 MCP Server 传输层重写实录:超时率 12% → 0.3%
前端·后端