使用async 实现事件池

1,194 阅读1分钟

前段时间小伙伴面试,在群里问一个事件池的问题,请看下面代码

new Queue()
.task(1000,()=>console.log(1))
.task(2000,()=>console.log(2))
.task(3000,()=>console.log(3))
.start()
实现该函数,start()后等1秒输出1,再等2秒输出2,再等3秒输出3.

事件池问题

好好的看了一下,其实就是一个事件池问题,如何实现一个事件池,看代码
class Queue{
    constructor() {
        this.list = [];
      }
      delay = (times, callBack) =>
        new Promise((res, rej) => {
          setTimeout(() => {
            callBack();
            res();
          }, times);
        });
      task = (times, callBack) => {
        this.list.push({ times, callBack });
        return this;
      };
      start = async () => {
        let i=0;
        while(i<this.list.length){
          const {times, callBack }= this.list[i]
          await this.delay(times, callBack);
          i++
        }
  };
}

看图