鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ js鏈?zhǔn)秸{(diào)用問題

js鏈?zhǔn)秸{(diào)用問題

寫一個鏈?zhǔn)秸{(diào)用,調(diào)用方式如下:

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這個節(jié)點(diǎn)上,盡管用了promise還是不能及時返回this指針,導(dǎo)致sleep(3).eat('...')時報錯說沒有eat函數(shù)。

請問應(yīng)該怎么解決呢?

回答
編輯回答
夢一場

你不應(yīng)該返回this,也就是Man對象,而是應(yīng)該另外包裝一個對象并返回

2017年10月2日 13:36
編輯回答
尕筱澄

建議了解promise的用法。

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

明顯你的sleep是沒有動作。如果你要用promise設(shè)計暫停,建議你自己建一個簡單的流程管控,自己寫一個then的鏈?zhǔn)?/p>

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
    }
}
2018年4月26日 18:33