admin管理员组文章数量:1392007
How does the scope of the Q promises work? As far as I know the callback of the "then" is called by window, like a setTimeout.
In this example (just an example to understand how it works):
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();
To have the text in the instance of foo I'm using bind:
var Foo = function () {
getFileText().then(this.showFile.bind(this));
};
Is there any other way?
How does the scope of the Q promises work? As far as I know the callback of the "then" is called by window, like a setTimeout.
In this example (just an example to understand how it works):
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();
To have the text in the instance of foo I'm using bind:
var Foo = function () {
getFileText().then(this.showFile.bind(this));
};
Is there any other way?
Share Improve this question edited Jul 4, 2013 at 17:46 Kaizo asked Jun 20, 2013 at 18:08 KaizoKaizo 4,1952 gold badges25 silver badges26 bronze badges1 Answer
Reset to default 8How does the scope of the Q promises work?
You're looking for the context.
I know the callback of the "then" is called by window
Well, on the global context, yes. It is specified to be called with undefined
as the thisArg
.
I'm using bind. Is there any other way?
Only the lengthy one, with a variable referencing the instance:
var that = this;
getFileText().then(function(text) {
that.text = text;
// or even longer:
// that.showFile(text);
});
本文标签: javascriptQ promisesHow does scope workStack Overflow
版权声明:本文标题:javascript - Q promises - How does scope work? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744734058a2622217.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论