【发布时间】:2015-09-26 18:42:34
【问题描述】:
使用 Node.js 的 Q library,当我尝试在 promise 中将对象原型函数传递给 .then 解析器时,它会丢失 this 的上下文:
Foo.prototype.outsideResolve = function() {
var that = this;
return q.Promise(function(resolve, reject) {
console.log(that); // {data: "foo"}
resolve();
});
};
Foo.prototype.insideResolve = function() {
var that = this;
return q.Promise(function(resolve, reject) {
console.log(that); // undefined
resolve();
});
};
Foo.prototype.async = function() {
var foo = this;
return q.Promise(function(resolve, reject) {
foo.outsideResolve()
.then(foo.insideResolve)
.then(resolve)
.fail(reject)
.done();
});
};
为什么会这样?这是预期的行为吗?你不应该能够在承诺解析中调用原型函数吗?有没有办法解决这个问题?
【问题讨论】:
-
.then(this.insideResolve.bind(this))
标签: javascript node.js promise