在promisecallback中访问“this”的对象(然后)

我想用Javascript创build一个对象。

其中一种方法应该执行承诺链。 链中的每个方法都必须访问作为对象成员的configurationvariables。 问题是, this运算符在PromiseMethod2被改变,我无法访问configurationvariables(它在PromiseMethod1正常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!'); } 

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

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

我不能使用bind方法,因为它看起来像执行callback时重新bind

有针对这个的解决方法吗? 为什么PromiseMethod1PromiseMethod2有区别?

真正的build议是不要使用thisnew的(如果你仍然想要inheritance,你可以使用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); 

在这里,我使用闭包,以及将父类词汇variables封装起来的能力。 而不是依靠JavaScript来在运行时基于哪个对象调用函数来神奇地将this注入到我的函数中,因为如问题所示,这并不总是有效的。

然而,我知道它是一种非常规的工作方式,所以如果你愿意坚持下去,你需要使用bind来告诉JavaScript this函数属于哪个值:

 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 。 您仍然需要绑定,因为您正在将函数传递给.then(f) ,并且接收函数的代码不知道应该使用哪个对象。 现在再看看我先前推荐的代码。 这里没有this东西,所以这些函数根本不依赖于被调用的对象,你可以把它们作为高阶函数传递,而不需要bind that = this 。 🙂

我会说这是不可能的。 您尝试混合两种不同的方法: 方法链接和承诺链接 。 我build议您查看您的架构。

唯一可见的东西(但我个人不喜欢它)如果你完全控制了你想要使用的所有promise,那么就是通过整个Promise链传递configuration值。

 SomeObject.prototype.init = function() { var that = this; return new Promise(function(resolve, reject) { resolve(that.config) }); } SomeObject.prototype.PromiseMethod1 = function(config, params) { return SomePromise(config, params); } SomeObject.prototype.PromiseMethod2 = function(config, someParams) { return SomePromise(config, someParams); } SomePromise = function(config, params) { return new Promise(function(resolve, reject) { //some code here resolve(config, newParamsFromSomeCode) }); } 

那么你可以打电话给:

 that.init().then(that.PromiseMethod1).then(that.PromiseMethod2); 

但是,它不像一个好的代码