gpt4 book ai didi

前端手写(十八)——Promise并行限制

转载 作者:知者 更新时间:2024-03-13 03:08:50 26 4
gpt4 key购买 nike

一、写在前面
一般我们做多个异步请求,此时我们常常采用的是Promise.all来进行处理,Promise.all会全部的一起执行,但是如果存在一些并行的限制,也就是说一次最多只能执行固定的数量,此时该如何做。这个比较类似于requestAnimationFrameapi,其使用的是递归,当上一帧指向完毕后,就会执行下一帧。保证帧与帧之间的紧密关系。
二、具体实现

class Scheduler {
  constructor() {
    //整个队列,存放任务的队列
    this.queue = []
    //最大可以并行的数量
    this.maxNum = 2
    //表示当前并行的数量
    this.curNum = 0
  }
  //向队列中添加任务
  add(promiseCreator) {
    this.queue.push(promiseCreator)
  }
  //开始执行
  start() {
    for(let i = 0; i < this.maxNum; i++) {
      this.getNext()
    }
  }
  //执行下一个
  getNext() {
    if (this.queue && this.queue.length && this.maxNum > this.curNum) {
      this.curNum++
      this.queue.shift()().then(() => {
        this.curNum--
        this.getNext()
      })
    }
  }
}

const timeout = time => new Promise(resolve => setTimeout(resolve, time))

const scheduler = new Scheduler()

const addTask = (time, order) => {
  scheduler.add(() => timeout(time).then(() => console.log(order)))
}

addTask(1000, 1)
addTask(500, 2)
addTask(300, 3)
addTask(400, 4)

scheduler.start()

26 4 0
文章推荐: JavaScript 入门
文章推荐: 并发编程-线程间的通信
文章推荐: String转Date问题
文章推荐: 操作系统 --- 文件操作和IO
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com