Q promise 的范围如何运作?据我所知,“then”的回调是由窗口调用的,就像 setTimeout。
在这个例子中(只是一个例子来理解它是如何工作的):
var getFileText = function() {
var deferred = Q.defer();
Server.readFile("foo.txt", "utf-8", function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
deferred.resolve(text);
}
});
return deferred.promise;
};
var Foo = function () {
getFileText().then(this.showFile);
};
Foo.prototype.showFile = function(text) {
this.text = text;
console.log(text);
};
var foo = new Foo();
要在 foo 的实例中包含文本,我正在使用绑定(bind):
var Foo = function () {
getFileText().then(this.showFile.bind(this));
};
还有其他办法吗?
最佳答案
How does the scope of the Q promises work?
您正在寻找上下文。
I know the callback of the "then" is called by window
嗯,在全局背景下,是的。它is specified以 undefined
作为 thisArg
调用。
I'm using bind. Is there any other way?
只有冗长的一个,带有一个引用实例的变量:
var that = this;
getFileText().then(function(text) {
that.text = text;
// or even longer:
// that.showFile(text);
});
关于javascript - Q promises - 作用域是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17220724/