Js chain call problem

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?


it is recommended to know the usage of promise.

    new Promise((res, rej)=> {
        setTimeout(()=> {
            res('');
        }, time*1000)
    }).then(val=> {
        return self;
    });

obviously your sleep has no action. If you want to use promise design pause, it is recommended that you create a simple process control and write a chain of then

.
class Man{
    constructor(name) {
        this.name = name;
        this.sayName();
        this.chain = Promise.resolve(this)
    }
    sayName() {
        console.log('hi '+this.name);
    }
    sleep(time) {
        this.chain = this.chain.then((v)=>{
            return new Promise((resolve,reject)=>{
                setTimeout(()=>{
                    resolve(v)
                },time*1000)
            })
        })
        return this;
    }
    eat(food) {
        this.chain = this.chain.then((v)=>{
            console.log(`eat ${food}`)
            return Promise.resolve(v)
        })
        return this
    }
}

you should not return this, that is, Man object, but should wrap another object and return

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b2c09e-2a827.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b2c09e-2a827.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?