【问题标题】:static async funcion in javascript classjavascript类中的静态异步函数
【发布时间】:2021-06-22 01:41:03
【问题描述】:

我在使用 javascript 类上的静态异步方法时遇到问题。 如果我删除 static 关键字,它可以在类中调用,但我将无法通过使用类来调用它。

我想要的结果是在使用 User.exist(email) 的类 itselt 和类 ex 的实例上使用 exists 方法。 foo.exist(email)

我认为哪里不对?

const userEmails = []

class User {
  constructor(fields) {
   this.email = fields.email;
   this.name = fields.name;
  }

  static async exist(email) {
    return setTimeout(function() {
      return userEmails.includes(email)
    }, 2000)
  }

  async storeEmail() {
    let userExist = await this.exist(this.email)

    if (userExist) {
      console.log('User exist')
    } else {
      users.push(this.email)
      console.log(userEmails)
    }
  }
};

let foo = new User({email: 'foo@bar.com', name: 'Foo Bar'})

foo.storeEmail()           // this.exist is not a function
User.exist('foo@bar.com')  // Works when used inside async function with await

【问题讨论】:

    标签: javascript class async-await javascript-objects


    【解决方案1】:

    当您将类的方法定义为静态成员时,它在使用this 关键字的实例上不可用。您可以使用类函数中的类名直接调用它,例如User.exist(this.email)

    const userEmails = []
    
    class User {
      constructor(fields) {
       this.email = fields.email;
       this.name = fields.name;
      }
    
      static async exist(email) {
        return setTimeout(function() {
          return userEmails.includes(email)
        }, 2000)
      }
    
      async storeEmail() {
        let userExist = await User.exist(this.email)
    
        if (userExist) {
          console.log('User exist')
        } else {
          users.push(this.email)
          console.log(userEmails)
        }
      }
    };
    
    let foo = new User({email: 'foo@bar.com', name: 'Foo Bar'})
    
    foo.storeEmail()           // this.exist is not a function
    User.exist('foo@bar.com')  // Works when used inside async function with 

    【讨论】:

    • 这很容易... :) 谢谢!
    • 很高兴能帮上忙 :-)
    【解决方案2】:

    你需要在静态上下文中调用你的静态函数,所以User.exist()而不是this.exist()

    const userEmails = []
    
    class User {
      constructor(fields) {
       this.email = fields.email;
       this.name = fields.name;
      }
    
      static async exist(email) {
        return setTimeout(function() {
          return userEmails.includes(email)
        }, 2000)
      }
    
      async storeEmail() {
        let userExist = await User.exist(this.email)
    
        if (userExist) {
          console.log('User exist')
        } else {
          users.push(this.email)
          console.log(userEmails)
        }
      }
    };
    
    let foo = new User({email: 'foo@bar.com', name: 'Foo Bar'})
    
    foo.storeEmail();          // OK
    User.exist('foo@bar.com'); // OK

    【讨论】:

    • 感谢您的宝贵时间! Shubham 有点快,会收到答案。
    猜你喜欢
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2013-07-31
    • 2021-01-09
    • 2021-06-04
    • 2022-01-01
    相关资源
    最近更新 更多