语音转化

38 阅读7分钟

1:devpress.csdn.net/vue/66caf22… 2:blog.csdn.net/Now_li/arti…

class PromiseQueue { constructor(maxConcurrency) { this.maxConcurrency = maxConcurrency; this.running = 0; this.queue = []; }

enqueue(task) {
    return new Promise((resolve, reject) => {
        this.queue.push(() => task().then(resolve, reject));
        this.runNext();
    });
}

runNext() {
    if (this.running >= this.maxConcurrency || this.queue.length === 0) {
        return;
    }
    const task = this.queue.shift();
    this.running++;
    task().finally(() => {
        this.running--;
        this.runNext();
    });
}

}

const createRequest = (id, delay) => () => { return new Promise((resolve) => { setTimeout(() => { console.log(Request ${id} completed); resolve(Result ${id}); }, delay); }); }; // 构造 100 个请求,每个请求有不同的延迟 const requests = Array.from({ length: 100 }, (_, i) => createRequest(i + 1, Math.random() * 1000));

// 使用队列 const queue = new PromiseQueue(5); // 并发数为 5 // const urls = Array(100).fill('example.com/api');

Promise.all( requests.map(url => queue.enqueue(() => url())) ).then(results => { console.log(results); });

Document * { margin: 0; padding: 0; }