【问题标题】:ES6 Class Promise Chain -- Accessing 'this' [duplicate]ES6 类 Promise 链——访问“this”[重复]
【发布时间】:2016-12-12 22:46:05
【问题描述】:

我想在我的第二个承诺中引用一个类属性。然而,在类函数 pTwo 中,'this' 是未定义的。我知道我在承诺范围内,我如何访问 PromiseChain 实例范围?

使用 ES6 和原生 Promise。

class PromiseChain {
    constructor(){
        this.food = 'Pasta';
        this.type = 'Italian';
    }

    pOne() {
        console.log('pOne');
        return Promise.resolve();
    }

    pTwo() {
        console.log('pTwo');
        try {
            console.log(this.food);
        } catch (e) {
            // can't read 'food' of undefined! 
            console.log(e);
        }
        return Promise.reject()
    }

    work() {
        console.log('Get to work!');
        this.pOne().then(this.pTwo).catch((error) => {
            console.log(error);
        })
    }
}

new PromiseChain().work();

【问题讨论】:

    标签: javascript class promise ecmascript-6


    【解决方案1】:

    这很简单,您需要将pTwo 的调用绑定到正确的范围,在Javascript 中我们可以使用bind() 方法来做到这一点。

    因此:

    this.pOne().then(this.pTwo.bind(this)).catch((error) => {
    

    会将您对 pTwo 的调用绑定到正确的范围,从而导致:

    Get to work!
    pOne
    pTwo
    Pasta
    undefined
    

    待打印;如果您希望最后一个未定义返回某些内容,请在您的拒绝参数中传递一条消息。

    如果你不想用大量的.bind(this) 弄乱你的代码库,你可以在当前范围内显式设置对this 的引用,并将它作为参数传递给你的每个promise;在您的情况下,在 work 方法中声明:

    work() {
        var that = this;
        console.log('Get to work!');
        this.pOne().then(this.pTwo(that).catch((error) => {
            console.log(error);
        }));
    }
    

    请注意,现在pTwo 接受that 的参数,现在在pTwo 内部我们可以执行以下操作:

    pTwo(parentScope) {
        console.log('pTwo');
        try {
            console.log(parentScope.food);
        } catch (e) {
            // can't read 'food' of undefined! 
            console.log(e);
        }
        return Promise.reject()
    }
    

    请注意,我们传递了参数parentScope,它允许我们引用正确的范围。

    【讨论】:

    • 嘿@Alex,非常感谢您的精神提升!假设你有 10 个 Promise 链接在一起,向每个 Promise 添加 .bind(this) 似乎有点冗长,有没有更简洁的方法可以做到这一点?
    • 如果你能找到一种更清洁的方式,我会很感兴趣!不幸的是,我的代码受到.bind 乱扔垃圾的困扰。 :)
    • 会的 :) 再次感谢!
    • 现在用另一种方法更新我的答案
    • 我会坚持使用 bind :D 我相信 'this.pTwo(that)' 的第二个选项意味着 pTwo 会立即被调用,而不是等待第一个承诺解决。
    猜你喜欢
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 2015-05-02
    • 2015-12-09
    • 2018-08-01
    相关资源
    最近更新 更多