LazyMan-Promise版
最近看到好多面经里都提到了LazyMan
自己用任务栈的方式确实简单解决了,但是突然看到有人被问到用Promise解决,就觉得很有意思了
网上也有人用Promise了,但结果用了栈去存Promise,大哥那还用Promise干什么..?
最后顺便把sleepAtFrist也解决了,可能方法不够完美,但目前自己没测到bug,如果有更好的方法希望有人指点!
关键在弄清宏任务和微任务之间的关系,我觉得这一个案例能讲透了
function LazyMan(name) {
this.promiseChain = new Promise((resolve) => {
setTimeout(() => {
this.atFirst = this.atFirst ? this.atFirst : 0;
console.log(`Hi, my name is ${name}`);
resolve() //因为需要在所有的then在同步代码中绑定好之后才能开始执行,所以放在setTimeOut里
}, this.atFirst * 1000);
})
}
LazyMan.prototype.eat = function (food) { //这里步骤应该没什么太复杂的
this.promiseChain.then((task) => {
console.log(`I eat ${food}`);
})
return this;
}
LazyMan.prototype.sleep = function (time) { //关键在sleep上,eat只需要为当前的chain进行then就好,但sleep要保证接下来chain为新promise,同时把自己的resolve交给上一个chain的then里
var tempP = this.promiseChain; //临时变量
this.promiseChain = new Promise((resolve) => {
tempP.then(() => {
setTimeout(() => {
console.log(`I sleep ${time}`);
resolve();
}, 1000 * time)
})
})
return this;
}
LazyMan.prototype.sleepAtFirst = function (time) { //sleepAtFirst应该有更优雅的解决方法吧..我这个实在有点low 但能解决问题
this.atFirst = time;
console.log('I sleep at first');
return this;
}
var lazyman = new LazyMan('jack')
lazyman.sleep(2).eat('meat').sleep(1).eat('apple').sleepAtFirst(1).eat('food') 刚开始的时候我在想用resolve的参数传递任务,最后层层的then进行累积再处理,但后来没继续下去,忘了是啥卡住我了 如果有大佬能指点一下那万分感谢!
查看14道真题和解析
