代码之家  ›  专栏  ›  技术社区  ›  John David

——等待这个。方法();在静态方法中不起作用

  •  6
  • John David  · 技术社区  · 7 年前

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

    它工作得很好,但当函数为 static 函数,它没有。有什么原因吗?此外,正确的使用方法是什么 等候 内部a 静止的 作用

    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();
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   jfriend00    7 年前

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

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

    如果你也 resolveAfter2Seconds() static ,那么它可能会起作用,因为 在…内 asyncCall() 类名 所以 这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"
      }
    }
    

    或者,您可以访问原型并从那里调用它,因为它实际上是一个静态方法(不引用 全部):

      static async asyncCall() {
        console.log('calling');
        var result = await MyClass.prototype.resolveAfter2Seconds();
        console.log(result);
        // expected output: "resolved"
      }
    
        2
  •  3
  •   CertainPerformance    7 年前

    你在打电话 await this.resolveAfter2Seconds(); 就好像 this 是的实例化 MyClass ,但在your'e调用它的上下文中,它不是- resolveAfter2Seconds 是上的方法 原型 属于 类名 ,它不是类本身的属性。改为调用prototype方法:

    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();