异步任务队列:
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 = ''
}
}