javascript - 访问 promise 回调中对象的 'this'(然后)

标签 javascript node.js promise

我想用 Javascript 创建一个对象。

其中一个方法应该执行一个 promise 链。链中的每个方法都必须访问作为对象成员的配置变量。 问题是,this 运算符在 PromiseMethod2 中被更改,我无法访问配置变量(它在 PromiseMethod1 中正常工作)。

这是我的代码:

var SomeObject(config) {
    var that = this;
    that.config = config;
}

SomeObject.prototype.SomeMethod = function() {
    var that = this;

    that.PromiseMethod1()
      .then(that.PromiseMethod2)
      .catch(console.error);
    }

SomeObject.prototype.PromiseMethod1 = function() {
    var that = this;
    config = that.config;

    return SomePromise();
}

SomeObject.prototype.PromiseMethod2 = function(someParams) {
    var that = this;
    config = that.config;
    params = someParams;

    return SomePromise();
}


var someObject = new SomeObject(someConfig);
someObject.SomeMethod().then(function () {
    console.log('Done!');
}

我想在链中使用方法委托(delegate)而不只是执行:

 that.PromiseMethod1().then(function(response) { return that.PromiseMethod2(that, response); };

我不能使用 bind 方法,因为它看起来像是在执行回调时重新绑定(bind)。

有解决办法吗? 为什么 PromiseMethod1PromiseMethod2 有区别?

最佳答案

真正的建议是不要使用thisnew(你可以使用Object.create 如果你还想继承):

var SomeObject = function(config) {
    return {
        PromiseMethod1: function(){
            return somePromise(config.foo);
        },
        PromiseMethod2: function(x){
            return someOtherPromise(config.bar, x);
        }
    }
}

var instance = SomeObject({config: true});
instance.PromiseMethod1().then(instance.PromiseMethod2);

我在这里使用闭包,以及它们封装其父词法范围变量的能力,这对我有利。而不是依靠 JavaScript 在运行时根据调用函数的对象神奇地将 this 注入(inject)我的函数,因为正如您的问题所证明的那样,这并不总是有效。

但是,我知道这是一种非常规的工作方式,所以如果你更愿意坚持使用 this,你需要使用 bind 来告诉神奇的 this 函数所属的 JavaScript:

var SomeObject function(config) {
    this.config = config;
}

SomeObject.prototype.PromiseMethod1 = function(){
    return somePromise(this.config.foo);
}

SomeObject.prototype.PromiseMethod1 = function(x){
    return someOtherPromise(this.config.bar, x);
}

var instance = new SomeObject({config: true});
instance.PromiseMethod1().then(instance.PromiseMethod2.bind(instance)); //<- :(

在您的示例 SomeMethod 中,您实际上并未使用 bind。您仍然需要绑定(bind),因为您将函数传递给 .then(f),并且接收该函数的代码不再知道它应该为 this< 使用哪个对象。现在再看看我之前推荐的代码。那里没有 thisses,因此这些函数根本不依赖于调用它们的对象,您可以根据需要将它们作为高阶函数传递无需 bindthat = this。 :)

关于javascript - 访问 promise 回调中对象的 'this'(然后),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34381595/

相关文章:

javascript - Neo4j虚拟机在windows azure中性能不佳

javascript - 如何从 Firestore Node.js 获取时间戳格式数据

javascript - 从连续的 jQuery ajax 调用返回 promise ?

ios - PromiseKit for In Loop 实现时

javascript - Firebase 函数发送后无法设置 header

javascript - 加密缺少全局变量名

javascript - 停止JS中的长轮询功能

node.js - 测试在 Node 中使用 mocha/supertest 重定向的请求

node.js - 无法使用 $project 获取特定的数据库值

javascript - Promise.all 在同一个数组上