小编shu*_*ima的帖子

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

我想在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!');
}
Run Code Online (Sandbox Code Playgroud)

我想在链中使用方法委托而不是仅执行:

 that.PromiseMethod1().then(function(response) { return that.PromiseMethod2(that, response); }; …
Run Code Online (Sandbox Code Playgroud)

javascript node.js promise

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

javascript ×1

node.js ×1

promise ×1