【问题标题】:Using this in promise scope with babel [duplicate]在 babel 的承诺范围内使用 this [重复]
【发布时间】:2016-09-27 16:44:41
【问题描述】:

我在使用 Babel 时发现了一个我还没有解决的问题。

问题是我在类方法中使用了 Promise,我需要访问 Promise 内的类的 this 对象来调用类函数。

代码是

class SecurityService {
    constructor($q) {
        this.$q = $q;
    }

    isAuthenticated() {
        return true;
    }

    requestCurrentUser() {
        return this.$q.when({});
    }

    requireAuthenticatedUser() {
        let deferred = this.$q.defer();

        this.requestCurrentUser()
        .then(
          function (user) {
            if (this.isAuthenticated()) {
              this.$log.debug('Security: Access granted for user.');
              return deferred.resolve(user);
            }

            return deferred.reject();
          }
        );
    }
}

当我调用 requireAuthenticatedUser 方法时,它在执行 this.isAuthenticated() 时失败,因为它试图在承诺范围内找到它。

Babel 通常将 this 变量包装在一个上层作用域变量中,执行如下操作:

var _this4 = this;

允许在子范围内使用,但它已经检查了仅在使用回调时执行此操作,而不是承诺。

是否需要导入任何预设或任何其他内容才能使其正常工作?

【问题讨论】:

  • 取决于您的目标(即 ES5 或 ES2015 或其他),但您可以使用箭头函数,例如 .then((user) => { if (this.isAuthenticated...
  • "它只在使用回调时执行此操作,而不是 Promise。" - 不。当您使用箭头函数而不是普通函数时,它会这样做。它与承诺无关。
  • 谢谢!在我发布问题后,我注意到我没有使用箭头函数:(现在效果很好。我会听从你关于承诺的建议,谢谢@Bergi

标签: javascript angularjs promise babeljs


【解决方案1】:

您可以在调用方法之前手动将 this 分配给变量(与分配 $q.defer() 的方式相同)。

requireAuthenticatedUser() {
  let deferred = this.$q.defer();
  var securityservice = this;

        this.requestCurrentUser()
        .then(
          function (user) {
            if (securityservice.isAuthenticated()) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    相关资源
    最近更新 更多