javascript - 从返回的 promise 中设置成员变量

标签 javascript node.js promise this q

我有一个问题,我觉得与 javascript 的特性有关。基本上,我试图在 Promise 的 then 函数中设置成员/类变量。例如:

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

        return oauthObj;
      });

其中 this.setOauthObj(oauthObj); 设置外部对象的成员变量。现在我想也许我的问题是 this 是问题,因为我认为 this 指的是 then 函数中的函数。所以我的问题是,如何在 Promise 的 then 函数中设置成员变量?或者说有可能吗?

我想要完成此任务的原因是因为我希望从对象的实例中设置此变量,因此我不必将其作为参数传递给每个方法调用。

最佳答案

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.

至少有两种方法可以解决该问题:

Bind

假设 this.intuitAuth 中使用的 this 是所需的 this,那么您可以将函数作用域绑定(bind)到该作用域,如下所示:

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

保留对所需this的引用。

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

现在,其中任何一个都可能解决您当前的问题。但您需要了解问题存在的原因,因此您应该阅读更多有关 how the value of this is set in a scope 的内容。 .

关于javascript - 从返回的 promise 中设置成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32024483/

相关文章:

javascript - express 返回帖子信息由另一个功能处理

javascript - node js 从 302 重定向获取 cookie

javascript - AngularJS-ng :model - Field is readonly when bound to $q promise?

javascript - 返回 Promise 说 Promise Pending,Node js?

Angularjs $q.all

javascript - 当用户导航到 react 路由器中的特定路线时,不会呈现任何 child

javascript - 在 javascript 或 jquery 中滚动到具有特定 id 的 html 元素

javascript - 使用 google Sheets javascript 添加而不将其发布给公众

javascript - 使用 Django 静态文件动态设置图像时,只有绝对路径适用于 Jquery

node.js - Cheerio如何忽略某个标签的元素