ES6 / Bluebird承诺的对象方法 [英] Object method with ES6 / Bluebird promises

查看:113
本文介绍了ES6 / Bluebird承诺的对象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows上使用节点v0.11.14-nightly-20140819-pre harmony flag。

I am using node v0.11.14-nightly-20140819-pre on Windows with harmony flag.

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

I have JavaScript object with two methods defined in its prototype:

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 of 服务对象返回一个承诺。

serviceMethod of Service object returns a promise.

当我使用用户对象如下:

let user = new User(args);
user.method1();

in 对象的method2 用户调用时结束 undefined 然后一旦履行承诺。

this in method2 of object User ends up undefined when called by then once promise is fulfilled.

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

I tried using both ES6 and Bluebird promise implementation.

为什么这个在这种情况下最终是 undefined

Why this ends up being undefined in this case?

推荐答案


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

Why this ends up being undefined in this case?

因为你传递了一个函数,而不是一个方法绑定到一个实例。此问题甚至不是特定于承诺的,请参阅如何在回调中访问正确的`this`上下文?解决方案:

Because you're passing a function, not a method-bound-to-an-instance. This problem is not even promise-specific, see How to access the correct `this` context inside a callback? for the generic solution:

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

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

但是, Bluebird确实提供了另一种方法来调用该函数作为一种方法:

However, Bluebird does offer an other way to call the function as a method:

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

这篇关于ES6 / Bluebird承诺的对象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆