promise-实现调用队列

实现一个类
const boy = new PlayBoy('Tom');
boy.sayHi().sleep(1000).play('王者').sleep(2000).play('跳一跳')

// 输出
// 大家好我是Tom
// 1s 之后
// 我在玩王者
// 2s 之后
// 我在玩跳一跳

class PlayBoy {
  constructor(name) {
    this.name = name;
    this.queue = Promise.resolve();
  }

  sayHi() {
    console.log(`大家好我是${this.name}`);
    return this;
  }

  sleep(seconds) {
    this.queue = this.queue.then(res => new Promise((resolve) => {
      console.log(`${seconds} 之后`);
      setTimeout(resolve, seconds)
    }));
    return this;
  }

  play(name) {
    this.queue = this.queue.then(res => {
      console.log(`我在玩${name}`);
    })
    return this;
  }
}

posted @ 2023-02-03 10:05  laiyaoWeb  阅读(68)  评论(0)    收藏  举报