JS控制并发请求数量

原理:使用一个队列维护所有的请求,然后使用async/await或者promise对请求进行控制, 当前面的请求完成就从队列中出队下一个请求

class LimitResquest {
  constructor(limit) {
    this.limit = limit
    this.currentSum = 0
    this.requests = []
  }

  request (reqFn) {
    if (!reqFn || !(reqFn instanceof Function)) {
      console.error('当前请求不是一个Function', reqFn)
      return
    }
    this.requests.push(reqFn)
    if (this.currentSum < this.limit) {
      this.run()
    }
  }

  async run() {
    try {
      ++this.currentSum
      const fn = this.requests.shift()
      await fn()
    } catch(err) {
      console.log('Error', err)
    } finally {
      --this.currentSum
      if (this.requests.length > 0) {
        this.run()
      }
    }
  }
}

使用:可以看到请求方法会按限制的数量进行请求

let a = () => new Promise((resolve) => {
  setTimeout(() => {resolve(1)}, 1000)
}).then((data) => console.log(data))


let b = () => new Promise((resolve) => {
  setTimeout(() => {resolve(2)}, 1000)
}).then((data) => console.log(data))


let c = () => new Promise((resolve) => {
  setTimeout(() => {resolve(3)}, 1000)
}).then((data) => console.log(data))


let d = () => new Promise((resolve) => {
  setTimeout(() => {resolve(4)}, 1000)
}).then((data) => console.log(data))

let limitResquest = new LimitResquest(2)
limitResquest.request(a)
limitResquest.request(b)
limitResquest.request(c)
limitResquest.request(d)
limitResquest.request(a)
limitResquest.request(b)
limitResquest.request(c)
limitResquest.request(d)

 

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值