babel ES6 中promise this指向问题
 发布于 8 年前  作者 Aoqin  4591 次预览  最后一次回复是 8 年前  来自 问答 

想请教下,用babel 处理 Class中 有promise 这种的时候,用lam,和bind方法都无法解决this指向问题。 在上层定义 self=this 可以. class test { construct(){ this.user={ name:‘test’ }; } getInfo(){ promise.then(data=>{ promise2 }).then( this.test() ) ) } test (){ console.log(this.user) } }

一般是怎么处理这种方式的啊,纠结了。

2 回复
i5ting

自己绑定this上下文吧

    _exec() {
        let self = this;

        debug('Pagelet ' + this.domid + ' fetch');

        // 1) this.before
        // 2)fetch,用于获取网络数据,可选
        // 3) parse,用于处理fetch获取的数据
        // 4)render,用与编译模板为html
        // 5)this.end 通知浏览器,写入完成

        return self.before()
            .then(self.fetch.bind(self))
            .then(self.parse.bind(self))
            .then(self.render.bind(self))
            .then(self.end.bind(self))
            .catch(self.catchFn)
    }
Aoqin

@i5ting 谢谢,我试试