【问题标题】:“await this.method();” doesn’t work in static method“等待 this.method();”在静态方法中不起作用
【发布时间】:2018-09-12 04:59:01
【问题描述】:

我知道 ES6 await 特性,我想在我在类中创建的函数中使用它。

它工作得很好,但是当函数是 static 函数时,它就不行了。有什么理由吗?另外,在static 函数中使用await 的正确方法是什么?

class MyClass {
  resolveAfter2Seconds() {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve('resolved');
      }, 2000);
    });
  }

  static async asyncCall() {
    console.log('calling');
    var result = await this.resolveAfter2Seconds();
    console.log(result);
    // expected output: "resolved"
  }
}

MyClass.asyncCall();

【问题讨论】:

  • 它应该可以工作。它在什么方面不起作用?

标签: javascript static async-await es6-promise es6-class


【解决方案1】:

您可以在静态函数中使用await。那不是你的问题。

但是,静态函数中的thisMyClass,所以this.someMethod() 正在寻找另一个静态方法,而不是实例方法,而resolveAfter2Seconds() 是实例方法,而不是静态方法,所以this.resolveAfter2Seconds() 赢了找不到那个方法,因为这就像调用不存在的MyClass.resolveAfter2Seconds()

如果您还将resolveAfter2Seconds() 设为static,那么它可能会起作用,因为asyncCall() 中的thisMyClass,所以this.resolveAfter2Seconds() 正在寻找另一种静态方法。

这应该可以在您使resolveAfter2Seconds 也成为静态的情况下工作:

class MyClass {

  static resolveAfter2Seconds() {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve('resolved');
      }, 2000);
    });
  }

  static async asyncCall() {
    console.log('calling');
    var result = await this.resolveAfter2Seconds();
    console.log(result);
    // expected output: "resolved"
  }
}

或者,您可以进入原型并从那里调用它,因为它实际上是一个静态方法(根本不引用 this):

  static async asyncCall() {
    console.log('calling');
    var result = await MyClass.prototype.resolveAfter2Seconds();
    console.log(result);
    // expected output: "resolved"
  }

【讨论】:

    【解决方案2】:

    您正在调用 await this.resolveAfter2Seconds();,就好像 thisMyClass 的实例化,但在您调用它的上下文中,它不是 - resolveAfter2Secondsprototype of MyClass,它不是类本身的属性。改为调用原型方法:

    class MyClass {
      resolveAfter2Seconds() {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('resolved');
          }, 2000);
        });
      }
      static async asyncCall() {
        console.log('calling');
        var result = await this.prototype.resolveAfter2Seconds();
        console.log(result);
        // expected output: "resolved"
      }
    
    }
    MyClass.asyncCall();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-27
      • 1970-01-01
      • 2014-08-17
      • 2012-06-17
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多