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 badges
Add a ment  | 

1 Answer 1

Reset to default 8

How 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