简体   繁体   中英

Setting Member Variable from within returned promise

I have an issue that I feel deals with the idiosyncrasies of javascript. Basically, I am trying to set a member/class variable to from within a then function of a promise. For example:

 this.intuitAuth.authenticate()
      .then(function(oauthObj){
        this.setOauthObj(oauthObj);

        return oauthObj;
      });

Where this.setOauthObj(oauthObj); sets the member variable for the outside object. Now I think maybe my problem is with this being the problem since I am thinking this refers to the function within the then function. So my question is, how can I set a member variable from within then function of a promise? Or is it even possible.

The reason I want to accomplish this is because I would like to have this variable be set from within the object's instance, so I dont have to pass it in to every method call as an argument.

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

There are at least two ways you can solve the problem:

Bind

Assuming this as used in this.intuitAuth is the desired this , then you may bind the function scope to that as follows:

this.intuitAuth.authenticate()
    .then(function(oauthObj){
        this.setOauthObj(oauthObj);    
        return oauthObj;
     }.bind(this));

Keep a reference to the desired this .

var _this = this;
this.intuitAuth.authenticate()
    .then(function(oauthObj){
        _this.setOauthObj(oauthObj);    
        return oauthObj;
     });

Now either of those would more than likely solve your current issue. But you need to understand why the problem exists, hence you should read more about how the value of this is set in a scope .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM