【发布时间】:2016-03-26 16:42:22
【问题描述】:
我想用 Javascript 创建一个对象。
其中一个方法应该执行一个承诺链。链中的每个方法都必须访问作为对象成员的配置变量。
问题是,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!');
}
我想在链中使用方法委托而不是仅仅执行:
that.PromiseMethod1().then(function(response) { return that.PromiseMethod2(that, response); };
我不能使用bind 方法,因为它看起来在执行回调时会重新绑定。
有解决办法吗?
为什么PromiseMethod1 和PromiseMethod2 有区别?
【问题讨论】:
-
你如何解决
SomePromise? -
每种方法可能做不同的事情。大多数情况下,我使用'new Promise(resolve,reject)'然后解决(somePrams)。或者我使用第三方承诺,如 ElasticSearch 或 Request-Promise
-
你断言你不能使用bind,但是你试过了吗?看起来这是正确的解决方案。
-
嗨。是的,我试过了。没用。
-
请准确展示您的尝试。
标签: javascript node.js promise