三七互娱前端笔试题 利用Promise实现会休息会工作的英雄

class Hero {
    constructor(name) {
        this.name = name;
        this.sum = 0;
        this.promise = Promise.resolve();
    }
    sleep(time) {
        this.promise = this.promise.then(function() {
            console.log('在床上睡' + time + '毫秒...');
            return new Promise(function(resolve) {
            setTimeout(resolve, time);
        });
        return this;
    }
    kill(num) {
        var that = this;
        this.promise = this.promise.then(function() {
            that.sum += num;
            console.log(`${that.name} 已干掉 ${that.sum} 只怪兽!`);
            return Promise.resolve();
        });
        return this;
    }
}

var hero = new Hero('超人');
hero
.kill(3)
.sleep(1000)
.kill(3)
.sleep(1000)
.kill(3)
.sleep(1000)
.kill(3)
.sleep(1000);

猜你喜欢

转载自blog.csdn.net/weixin_39181833/article/details/80115067