“等待 this.method();” 在静态方法中不起作用

Joh*_*vid 6 javascript static async-await es6-promise es6-class

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

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

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();
Run Code Online (Sandbox Code Playgroud)

jfr*_*d00 4

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

但是,this在静态函数中,寻找另一个静态方法,而不是实例方法,并且 MyClass是实例方法,不是静态方法,所以不会找到该方法,因为这就像调用不存在的方法一样。this.someMethod()resolveAfter2Seconds()this.resolveAfter2Seconds()MyClass.resolveAfter2Seconds()

如果您也制作resolveAfter2Seconds()be static,那么它可能会起作用,因为this内部asyncCall()is MyClasssothis.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"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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