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进行累积再处理,但后来没继续下去,忘了是啥卡住我了
如果有大佬能指点一下那万分感谢!


#面试题##前端##笔记##面试题目#
全部评论
主要有两个问题 1. sleep里面promise的传递太复杂了,不用这么写吧 2. sleepfirst耦合太严重了,没有队列方式的清晰。 其实按我的理解,如果有promise相当于把队列的数据结构改成链表。 就必须实现一个尾插和一个头插。尾***这里也做了。 头插因为promise立即执行的机制,必须和尾插错开,用settimeout就可以了。 另外你的sleepfirst多次就不管用了,可以调一下,附上一个我的实现
点赞 回复
分享
发布于 2021-08-05 11:06

相关推荐

3 28 评论
分享
牛客网
牛客企业服务