javascript - 带有 ES6/Bluebird promise 的对象方法

标签 javascript node.js promise bluebird

我在带有 harmony 标志的 Windows 上使用 node v0.11.14-nightly-20140819-pre

我的 JavaScript 对象在其原型(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);
}
Service 对象的

serviceMethod 返回一个promise。

当我使用 User 对象时,如下所示:

let user = new User(args);
user.method1();
对象 Usermethod2 中的

this 在被 then 调用时以 undefined 结束> 一旦 promise 兑现。

我尝试同时使用 ES6Bluebird promise 实现。

为什么 this 在这种情况下会变成 undefined

最佳答案

Why this ends up being undefined in this case?

因为您传递的是函数,而不是方法绑定(bind)到实例。这个问题甚至不是特定于 promise 的,请参阅 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);

关于javascript - 带有 ES6/Bluebird promise 的对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27149034/

相关文章:

node.js - 如何让 Istanbul 报告 Lab/Hapi.js 测试的覆盖范围?

javascript - passport-slack 返回 Cannot GET/auth/slack

node.js - 需要子文件夹中的 node_module

javascript - 仅在获取所有文件后执行命令

javascript - 如何在 AngularJS 循环中调用第二个顺序 Promise 设计模式方法?

javascript - 使用 Javascript API 时出现 Google 驱动器权限问题

javascript - jquery下拉菜单瞬间闪烁

javascript - jQuery 自动完成 mustmatch 没有任何效果

javascript - 基本 Mocha TDD 接口(interface)

javascript - NodeJS : Unhandled promise rejection