关于串并行

// 回调
asyncFun = (arg, cb) => {
  setTimeout(()=>{
    console.log(`参数为${arg}`)
    cb(arg * 2)
  },1000)
}
let items = [1,2,3,4,5,6]
var cbResults = []
final = (result) => {
  console.log(`完成${result}`)
}
串行执行任务队列items
series = (item) => {
  if (item) {
    asyncFun(item, (cbParams) => {
      cbResults.push(cbParams)
      return series(items.shift())
    })
  } else {
    final(cbResults)
    console.timeEnd('sync')
  }
}
console.time('sync');
series(items.shift()) //6.012s
并行执行任务队列items
let len = items.length
console.time('asyncFn');
items.forEach((item) => {
  asyncFun(item, (cbParams) => {
    cbResults.push(cbParams)
    if (cbResults.length == len) {
      final(cbResults)
      console.timeEnd('asyncFn');
    }
  })
})
// 1.003s
串行与并行的结合,即每次设定最多能并行n个异步任务
let running = 0 //串行的任务个数
let limit = 2 // 最多能并行2个异步任务(每两个一输出)
console.time('control')
launcher = () => {
  while(running < limit && items.length > 0) {
    let item = items.shift()
    running++
    asyncFun(item, (cbParams) => {
      cbResults.push(cbParams)
      running--
      if (items.length > 0) {
        launcher()
      }else if(running == 0){
        final(cbResults);
        console.timeEnd('control');
      }
    })
  }
}
launcher();
// 3.005s

你可能感兴趣的:(关于串并行)