当前位置: 首页 > article >正文

用JavaScript实现异步锁

场景

连续多次的响应时间不确定的异步请求,按请求顺序依次返回响应结果。

代码

class AsyncQueue {
    constructor() {
        this.queue = []; // 请求队列  
        this.isProcessing = false; // 当前是否在处理请求  
    }

    // 添加请求到队列  
    enqueue(asyncFunc) {
        this.queue.push(asyncFunc);
        this.processQueue(); // 开始处理队列  
    }

    // 处理队列中的请求  
    processQueue() {
        if (this.isProcessing || this.queue.length === 0) {
            return; // 如果正在处理或队列为空,直接返回  
        }

        this.isProcessing = true; // 标记为正在处理请求  
        const currentFunc = this.queue.shift(); // 从队列中取出第一个请求  

        // 执行当前请求 
        currentFunc().then(result => {
            console.log('Request processed:', result);
        }).catch(error => {
            console.error('Request error:', error);
        }).finally(() => {
            this.isProcessing = false; // 操作完成,重置为未处理状态  
            this.processQueue(); // 继续处理下一个请求  
        });
        
    }
}

// 示例异步函数  
const fetchData = (id) => {
    const delay = Math.random() * 1000;  // 模拟不同响应时间
    console.log(delay);
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(`Result from fetchData with id: ${id}`);
        }, delay);
    });
};

// 使用示例  
const asyncQueue = new AsyncQueue();

// 模拟多个请求  
const makeRequest = (id) => {
    asyncQueue.enqueue(() => fetchData(id));
};

// 发起多个请求  
makeRequest(1);
makeRequest(2);
makeRequest(3);
makeRequest(4);
makeRequest(5);

预期输出

> Request processed: Result from fetchData with id: 1
> Request processed: Result from fetchData with id: 2
> Request processed: Result from fetchData with id: 3
> Request processed: Result from fetchData with id: 4
> Request processed: Result from fetchData with id: 5

http://www.kler.cn/a/538067.html

相关文章:

  • Axure原型图怎么通过链接共享
  • 【算法】【高精度】acwing算法基础 794. 高精度除法
  • Shapefile格式文件解析和显示
  • Docker从入门到精通- 容器化技术全解析
  • 四次挥手详解
  • 【大模型】Ubuntu下安装ollama,DeepSseek-R1:32b的本地部署和运行
  • aio-pika 快速上手(Python 异步 RabbitMQ 客户端)
  • 模型 反脆弱
  • 前端开发中的主题切换:如何实现灵活的主题变化?
  • 半导体制造工艺讲解
  • sqli-lab靶场学习(五)——Less15-17(post方法盲注、修改密码)
  • 从DeepSeek上线亚马逊云科技,看大模型争霸背后的隐形战场
  • 青少年编程与数学 02-008 Pyhon语言编程基础 23课题、数据库操作
  • 蓝桥杯之c++入门(六)【string(practice)】
  • NFT Insider #168:The Sandbox 推出新春{金蛇礼服}套装;胖企鹅合作 LINE Minini
  • java基础3(黑马)
  • 2014 年中央、国家机关公务员录用考试 《申论》(市地以下)真题详解
  • 人工智能:从概念到未来
  • lvglllllllllll
  • GRU 和 LSTM 公式推导与矩阵变换过程图解
  • 2024 JAVA面试题
  • 【C++入门讲解】
  • uniapp商城之购物车模块
  • Vmware 与 Device/Credential Guard不兼容解决方法
  • CSP晋级组比赛生成文件夹与文件通用代码Python
  • oCam:免费且强大的录屏软件