JavaScript 类中的静态异步函数

Pat*_*der 8 javascript class javascript-objects async-await

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

User.exist(email)我期望的结果是在类本身上使用和在类的实例上使用存在方法,例如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
Run Code Online (Sandbox Code Playgroud)

Shu*_*tri 6

当您将类的方法定义为静态成员时,它在使用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 
Run Code Online (Sandbox Code Playgroud)