js请求限流的2种方式
2022-1-29
最多2个请求同时并发
let queue = []
const limit = 2
let count = 0
const interface = (cont) => {
return () => new Promise((res, rej) => {
setTimeout(() => {
console.log(cont)
res()
}, 500)
})
}
const main = () => {
for (let i = 0; i < 10; i++) {
queue.push(interface(i))
}
const helper = () => {
if (count > limit || !queue.length) return void (0)
count++
queue.shift()().then(() => {
count--
helper()
})
}
for (let i = 0; i < limit; i++) {
helper()
}
}
main()
第二种方法
const interface2 = (cont) => new Promise((res, rej) => {
setTimeout(() => {
res(cont)
}, 500)
})
const main2 = () => {
const helper = async (fn) => {
if (count >= limit) {
await new Promise((resolve) => {
queue.push(resolve)
})
}
count++
await fn()
count--
console.log(queue)
if (queue.length > 0) {
queue.shift()()
}
}
for (let i = 0; i < 10; i++) {
helper(() => {
return interface2(i).then(res => {
console.log(res)
})
})
}
}
main2()