关于node.js:node之请求管理器

当同时有很多申请发动时,会重大升高每个申请的响应速度,或导致接口申请失败,所以须要管制申请并发数,createRequestManage函数能够创立一个全局的申请管理器,治理申请,申请超过下限时,会将申请放入队列。

function createRequestManage(limit) {
  let currentTotal = 0
  let todoList = []
  return {
    schedule(callback) {
      if (currentTotal > limit) {
        todoList.push(callback)
      } else {
        currentTotal++
        let next = () => {
          currentTotal--
          if (todoList.length > 0) {
            let cb = todoList.shift()
            cb().finally(next)
          }
        }
        callback().finally(next)
      }
    }
  }
}

如何应用:

const requestManage = createRequestManage(500)
request.schedule(()=> {
  axios.get('').then(res=>{})
})

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理