Q承诺 - 范围如何运作?

Kai*_*izo 3 javascript scope q

Q承诺的范围如何运作?据我所知,"then"的回调由window调用,就像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();
Run Code Online (Sandbox Code Playgroud)

要在foo的实例中使用我正在使用bind的文本:

var Foo =  function () {
    getFileText().then(this.showFile.bind(this));
};
Run Code Online (Sandbox Code Playgroud)

还有其他方法吗?

Ber*_*rgi 8

Q承诺的范围如何运作?

你正在寻找上下文.

我知道窗口调用"then"的回调

那么,全球而言,是的.它被指定与被调用undefinedthisArg.

我正在使用bind.还有其他方法吗?

只有冗长的一个,带有引用实例的变量:

var that = this;
getFileText().then(function(text) {
    that.text = text;
    // or even longer:
    // that.showFile(text);
});
Run Code Online (Sandbox Code Playgroud)