记录-请求并发控制的实现

36 阅读1分钟
//模拟数据
const arr = Array.from({ length: 20 }, (_, index) => {
  const item = {
    id: index,
    content: `Item ${index + 1}`
  }
  return {
    id: index,
    func: () => new Promise(resolve => {
      setTimeout(() => {
        resolve(item)
      }, Math.random() * 5000)
    })
  }
})

//方式1
function multipleReq(reqs = [], max = 7) {
  const pool = reqs.splice(0, max)
  const start = (req) => {
    req.func().then((res) => {
      const i = pool.findIndex(item => item.id === req.id)
      pool.splice(i, 1)
      if (pool.length < max && reqs.length !== 0) {
        const [item] = reqs.splice(0, 1)
        pool.push(item)
        start(item)
      }
    })
  }
  for (let i = 0; i < pool.length; i++) {
    start(pool[i])
  }
}
multipleReq(arr)

//方式2
const multipleRequest = (reqs = [], max = 7) => {
  let curIndex = 0; let count = 0
  const start = () => {
    while (reqs[curIndex] && max > 0) {
      max--
      reqs[curIndex++].func().then(res => {
        max++
        count++
        if (count === reqs.length) {
          console.log('请求完成')
        } else {
          start()
        }
      })
    }
  }
  start()
}
multipleRequest(arr)