使用Promise.all实现请求的并发控制

给请求绑定回调,在请求完成时检查请求队列是否还有任务,有的话就加入到任务池里

function limitedRequest(taskArr, max) {
  let pool = []
  let len = Math.min(taskArr.length, max)
  for (let i = 0; i < len; i++) {
    pool.push((taskArr.shift())().then(r))
  }

  function r() {
    if (taskArr.length === 0) return
    console.log('新任务入池');
    pool.push((taskArr.shift())().then(r))
  }

  return Promise.all(pool)
}

let promise1 = () => new Promise(resolve => {
  setTimeout(() => {
    console.log('任务1完成');
    resolve()
  }, 1000)
})
let promise2 = () => new Promise(resolve => {
  setTimeout(() => {
    console.log('任务2完成');
    resolve()
  }, 2000)
})
let promise3 = () => new Promise(resolve => {
  setTimeout(() => {
    console.log('任务3完成');
    resolve()
  }, 4000)
})
let promise4 = () => new Promise(resolve => {
  setTimeout(() => {
    console.log('任务4完成');
    resolve()
  }, 4000)
})
let promise5 = () => new Promise(resolve => {
  setTimeout(() => {
    console.log('任务5完成');
    resolve()
  }, 4000)
})
let promise6 = () => new Promise(resolve => {
  setTimeout(() => {
    console.log('任务6完成');
    resolve()
  }, 3000)
})
let promise7 = () => new Promise(resolve => {
  setTimeout(() => {
    console.log('任务7完成');
    resolve()
  }, 2000)
})
let promise8 = () => new Promise(resolve => {
  setTimeout(() => {
    console.log('任务8完成');
    resolve()
  }, 1000)
})


let arr = [promise1, promise2, promise3, promise4, promise5, promise6,
            promise7, promise8]

limitedRequest(arr, 4)
//任务1完成
//新任务入池
//任务2完成
//新任务入池
//任务3完成
//新任务入池
//任务4完成
//新任务入池
//任务8完成
//任务6完成
//任务5完成
//任务7完成

你可能感兴趣的:(前端)