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);