导航栏: 首页 评论列表

异步任务队列

默认分类 2021/02/24 06:33

异步任务队列:

var aa = new Person()
aa.eat().sleep(3).work().sleep(3).eat().sleep(3).work()

代码实现:

class Person {
  constructor () {
    this.task = []
    this.status = ''
  }
  eat () {
    this.task.push(() => console.log('eat'))
    if (!this.status) this.run()
    return this
  }
  sleep (tt) {
    this.task.push(() => new Promise((resolve) => setTimeout(() => resolve(this), tt * 1000)))
    if (!this.status) this.run()
    return this
  }
  work () {
    this.task.push(() => console.log('work'))
    if (!this.status) this.run()
    return this
  }
  async run () {
    this.status = 'running'
    while (this.task.length) {
      await this.task.shift()()
    }
    this.status = ''
  }
}


>> 留言评论