javascript - Q promises - 作用域是如何工作的?

标签 javascript scope q

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 specifiedundefined 作为 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/

相关文章:

scope - 通过 <phingcall> 调用的目标不会在调用目标中设置属性

javascript - 刷新/定时器功能仅适用于 2 个提要中的 1 个 -- $q.all() 合并

javascript - Firefox Devtools 将大型 Javascript 文件显示为未定义

javascript - 如果我们从 html 页面调用 Angular 函数那么它将如何工作?

javascript - ember.js 的多个导出 - 我做错了什么?

node.js - 使用q.js时如何获取异常信息

arrays - NodeJS - 使用 Q 对对象数组执行异步操作,但有所不同

javascript - 在 JS 中使用 indexOf() - 否定空值是否明智以及如何操作?

java - 能否以某种方式限定最终参数以解决与匿名类成员的命名冲突?

perl - 更新 Perl 全局变量的正确方法