1、题目
lazyMan('Lazy').eat('app').firstSleep(1).eat('banner').sleep(2).eat('orange')
注意:
- 1、如果有调用firstSleep,无论firstSleep在什么位置,必须在执行完firstSleep延迟时间后,才开始按顺序执行
- 2、 遇到sleep必须延迟后再继续执行后面的函数
2、示例
lazyMan('Lazy').eat('apple').firstSleep(1).eat('banner').sleep(2).eat('orange')
// 比如上面 demo输出结果为:
Lazy第一次睡觉1s
Lazy第一次睡醒了
我的名字是Lazy
Lazy正在吃apple
Lazy正在吃banner
Lazy再次睡觉2s
Lazy再次睡醒
Lazy正在吃orange
3、实现
// lazy函数实现
function lazyMan(name){
// 实现链式调用方法肯定要返回一个对象,所以实例化构造函数
return new _lazyMan(name)
}
// 构造函数
function _lazyMan(name){
let flag = Promise.resolve()
this.name = name
// 事件队列
this.fun_stack = []
let self = this
function fn(){
console.log('我的名字是' + self.name)
// 因为要按顺序执行,所以返回promise
return Promise.resolve()
}
this.fun_stack.push(fn)
setTimeout(function(){
self.fun_stack.forEach(fn => {
// 实现按顺序执行
flag = flag.then(fn)
})
})
}
// 实现原型上的sleep函数
_lazyMan.prototype.sleep = function(time){
let self = this
function fn(){
return new Promise(function(resolve){
console.log(self.name + '再次睡觉')
setTimeout(function(){
console.log(self.name + '再次睡醒')
resolve()
}, time * 1000)
})
}
this.fun_stack.push(fn)
return this
}
// 实现原型上的firstSleep函数
_lazyMan.prototype.firstSleep = function(time){
let self = this
function fn(){
return new Promise(function(resolve){
console.log(self.name + '第一次睡觉')
setTimeout(function(){
console.log(self.name + '第一次睡醒了')
resolve()
}, time * 1000)
})
}
// 实现无论firstSleep在什么位置都要最先执行
this.fun_stack.unshift(fn)
return this
}
_lazyMan.prototype.eat = function(food){
let self = this
function fn(){
console.log(self.name + '正在吃' + food)
return Promise.resolve()
}
this.fun_stack.push(fn)
return this
}
4、测试
lazyMan('Lazy').eat('apple').firstSleep(1).eat('banner').sleep(2).eat('orange')