JavaScript 类中的静态异步函数

问题描述 投票:0回答:2

我在 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: '[email protected]', name: 'Foo Bar'})

foo.storeEmail()           // this.exist is not a function
User.exist('[email protected]')  // Works when used inside async function with await
javascript class async-await javascript-objects
2个回答
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: '[email protected]', name: 'Foo Bar'})

foo.storeEmail()           // this.exist is not a function
User.exist('[email protected]')  // 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: '[email protected]', name: 'Foo Bar'})

foo.storeEmail();          // OK
User.exist('[email protected]'); // OK

© www.soinside.com 2019 - 2024. All rights reserved.