题目:
要求1:按以下要求输出
human('Jack').eat().sleep(5).go().rest(10);
// I am Jack
// Eat
// 等 5 秒
// Sleep 1s
// Go
// 等 10 秒
// Rest 10s
要求2:eat/sleep/go/rest可以改变任意顺序
human('Jack').sleep(5).eat().rest(10).go();
解答:
function human(name){
return new Human(name)
}
function Human(name){
this.name = name
this.sayHello()
this.queue = Promise.resolve()
}
Human.prototype.sayHello = function(){
console.log(`I am ${this.name}`)
}
Human.prototype.eat = function(){
this.queue = this.queue.then(()=>{
return new Promise((resolve)=>{
console.log('Eat')
resolve()
})
})
return this
}
Human.prototype.sleep = function(time){
this.queue = this.queue.then(()=>{
return new Promise((resolve)=>{
setTimeout(()=>{
console.log(`Sleep ${time}s`)
resolve()
},time*1000)
})
})
return this
}
Human.prototype.go = function(){
this.queue = this.queue.then(()=>{
return new Promise((resolve)=>{
console.log('Go')
resolve()
})
})
return this
}
Human.prototype.rest = function(time){
this.queue = this.queue.then(()=>{
return new Promise((resolve)=>{
setTimeout(()=>{
console.log(`Rest ${time}s`);
resolve()
},time*1000)
})
})
return this
}
human('Jack').eat().sleep(5).go().rest(10);