限制并发请求的数量

限制并发请求的数量

// 限制并发请求数量
async function limitConcurrency(tasks, limit) {
    
    
    const results = [];
    const executing = new Set();

    for (const task of tasks) {
    
    

        const promise = Promise.resolve(task()).then((value) =>{
    
     results.push(value);} );

        // console.log(results)
        executing.add(promise);

        const clean = () => executing.delete(promise);
        promise.then(clean, clean);

        if (executing.size >= limit) {
    
    
            // console.log(executing)
            await Promise.race(executing);
        }
    }

    return Promise.all(results);
}

// 使用示例
const tasks = Array(10).fill(() => new Promise(resolve =>
    setTimeout(() => resolve(Math.random()), 1000)
));

limitConcurrency(tasks, 3)
    .then(results => console.log('所有任务完成:', results));