写一个链式调用,调用方式如下:
new Man('lan').sleep(3).eat('apple').sleep(3).eat('banana');
输出:
hello, lan -->(停顿3s) --> lan eat apple -->(停顿3s) --> lan eat banana
我的代码如下:
class Man {
constructor(name) {
this.name = name;
this.sayName();
}
sayName() {
console.log('hi '+this.name);
}
sleep(time) {
var self = this;
new Promise((res, rej)=> {
setTimeout(()=> {
res('');
}, time*1000)
}).then(val=> {
return self;
});
}
eat(food) {
console.log(this.name + '吃' + food);
return this;
}
}
new Man('兰兰').sleep(3).eat('饼干').sleep(3).eat('苹果');
问题出在sleep这个节点上,尽管用了promise还是不能及时返回this指针,导致sleep(3).eat('...')时报错说没有eat函数。
请问应该怎么解决呢?
建议了解promise的用法。
明显你的sleep是没有动作。如果你要用promise设计暂停,建议你自己建一个简单的流程管控,自己写一个then的链式