write a chained call as follows:
new Man("lan").sleep(3).eat("apple").sleep(3).eat("banana");
output:
hello, lan--> (pause 3s)-> lan eat apple-> (pause 3s)-> lan eat banana
my code is as follows:
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("");
the problem lies in the sleep node. Although promise is used, the this pointer cannot be returned in time, resulting in sleep (3). Eat (".") The Times mistakenly said that there was no eat function.
what should I do to solve this problem?