闽公网安备 35020302035485号
async const () => {
const list = [xxx] // list 是课程数组
const promiseList = list.map((item)=>{
return axios.get(`https://xxx?id=${item.id}`)
})
await Promise.all(promiseList)
// 执行后续操作
}
// 堆代码 duidaima.com
// 这里请求多个接口我用下列代码来模拟:
const fn = () => {
const arr = []
for(let i = 1;i < 100;i++){
arr.push(axios.get('/test/api' + i))
}
await Promise.all(arr)
// 执行后续操作
}
接着看一下每个接口所需的时间(由于接口是乱写的,所以报错很正常,主要是看一下请求时间):

import axios from 'axios'
export const handQueue = (
list // 请求总数
) => {
list = list || 0
const requestQueue = (maxNum) => {
maxNum = maxNum || 6 // 最大并发数
const queue = [] // 请求池
let current = 0 // 当前请求了多少条
const dequeue = () => {
while (current < maxNum && queue.length) {
current++
const currentPromise = queue.shift() // 出列
currentPromise()
.then(() => {
// 成功的请求逻辑
console.log('执行成功')
})
.catch((error) => {
// 失败
console.log(error)
})
.finally(() => {
current--
dequeue()
})
}
}
return (currentPromise) => {
queue.push(currentPromise) // 入队
dequeue()
}
}
const enqueue = requestQueue(6)
// console.log('enqueue:', enqueue)
for (let i = 0; i < list; i++) {
enqueue(() => axios.get('/api/test' + i))
}
}
// 使用时在页面调用handQueue即可
关于请求池花费的时间可以上移回去看两张对比图。const { res } = handQueue(list)
console.log(res)
由于异步是非阻塞的(在请求池中执行的就是多个网络请求),在执行打印的时候可能请求池中的请求都没来得及执行完,所以此时打印会出现拿不到值的情况。