import axios from 'axios' export const handQueue = ( reqs // 请求总数 ) => { reqs = reqs || [] const requestQueue = (concurrency) => { concurrency = concurrency || 6 // 最大并发数 const queue = [] // 请求池 let current = 0 const dequeue = () => { while (current < concurrency && queue.length) { current++; const requestPromiseFactory = queue.shift() // 出列 requestPromiseFactory() .then(() => { // 成功的请求逻辑 }) .catch(error => { // 失败 console.log(error) }) .finally(() => { current-- dequeue() }); } } return (requestPromiseFactory) => { queue.push(requestPromiseFactory) // 入队 dequeue() } } const enqueue = requestQueue(6) for (let i = 0; i < reqs.length; i++) { enqueue(() => axios.get('/api/test' + i)) } }
转自面试官:假如有几十个请求,如何去控制并发? - 掘金 (juejin.cn)
标签:queue,const,requestPromiseFactory,一次性,接口,reqs,current,强求,concurrency From: https://www.cnblogs.com/7788mmhh/p/18311960