用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

你可能感兴趣的:(JavaScript,javascript,前端,开发语言)