优雅的控制并发任务

/**
 * 并发启动任务,每完成一批任务后再启动下一批
 */
async function batchRun(tasks,batchSize){
    for(let i= 0;i<tasks.length;i+=batchSize){
        const batch = tasks.slice(i,i+batchSize);
        await Promise.all(batch.map(task => task()));
    }
}

/** 
 * 最多同时运行 n 个请求,每当有一个请求完成,就补上一个新的请求,直到所有请求完成。
 * */
async function concurrentRun(tasks, maxConcurrent){
    let nextIndex = 0;
    async function worker(){
        //执行完一个任务后,继续执行下一个任务
        while(nextIndex < tasks.length){
            const currentIndex = nextIndex++;
            await tasks[currentIndex]();
        }
    }
    //创建 maxConcurrent 个 worker,每个worker内部都会自动续接下一个任务
    const initialTasks = Array.from({length: maxConcurrent}, () => worker());
    await Promise.all(initialTasks);
}

 

posted @ 2025-07-24 20:33  我是格鲁特  阅读(11)  评论(0)    收藏  举报