批量请求--控制并发数实现
并发池实现
const promisePool = (taskList, limit) => { return new Promise(async (resolve, reject) => { const length = taskList.length /**当前并发池 */ const pool = [] /**结果数组 */ const res = new Array(length) /**完成的数量 */ let count = 0 for (let i = 0; i < length; i++) { const task = taskList[i](); //promise结束的回调 const handler = (data) => { pool.splice(pool.indexOf(task), 1) //任务执行完就删除 res[i] = data //不能使用res.push,否则不能保证结果顺序 count++ if (count === length) { resolve(res) } } task.then((data) => { handler(data) console.log(`第${i}个任务完成,结果为`, data); }, (err) => { handler(err) console.log(`第${i}个任务失败,原因为`, err); }) pool.push(task) //如果到达了并发限制,就等到池子中任意一个结束 if (pool.length >= limit) { await Promise.race(pool) } } }) }
模拟任务
const createTask = ()=>{ return async ()=>{ return await new Promise((resolve,reject)=>{ var i = Math.floor(Math.random()*5+2) setTimeout(()=>{ resolve(i) },i*1000) }) } }
测试
const testIt = async () => { const list = new Array(20).fill(0).map(() => createTask()) const res = await promisePool(list, 5) console.log('res', res); } testIt()