ES6 / Bluebird承诺的对象方法

时间:2014-11-26 12:18:07

标签: javascript node.js promise bluebird

我在Windows上使用节点v0.11.14-nightly-20140819-pre 并带有harmony标记。

我有JavaScript对象,其原型中定义了两个方法:

function User (args) {
    this.service= new Service(args);
}

User.prototype.method2 = function (response) {
    console.log(this); // <= UNDEFINED!!!!
};

User.prototype.method1 = function () {
    .............
    this.service.serviceMethod(args)
        .then(this.method2)
        .catch(onRejected);
};

function onRejected(val) {
    console.log(val);
}
serviceMethod对象的

Service返回一个承诺。

当我使用下面的User对象时:

let user = new User(args);
user.method1();
对象this的{​​{1}}中的method2在履行承诺后由User调用时结束undefined

我尝试使用 ES6 Bluebird 承诺实施。

为什么then在这种情况下最终成为this

2 个答案:

答案 0 :(得分:14)

  

为什么this在这种情况下最终成为undefined

因为你传递了一个函数,而不是一个方法绑定到一个实例。此问题甚至不是特定于承诺的,请参阅How to access the correct `this` context inside a callback?以获取通用解决方案:

….then(this.method2.bind(this))… // ES5 .bind() Function method

….then((r) => this.method2(r))… // ES6 arrow function

但是,Bluebird does offer是另一种将函数作为方法调用的方法:

this.service.serviceMethod(args)
    .bind(this)
    .then(this.method2)
    .catch(onRejected);

答案 1 :(得分:6)

我应该补充一点,这是一个通用的Javascript问题,也可以使用普通的javascript功能解决。例如,您也可以这样做:

User.prototype.method1 = function () {
    .............
    this.service.serviceMethod(args)
        .then(this.method2.bind(this))
        .catch(onRejected);
};

这使用内置于Javascript中的Function.prototype.bind()并呈现在每个函数上。这将创建一个函数存根(传递给.then()的函数存根,该存根将在调用this之前自动重新附加所需的method2()值。