javascriptclassasync-awaitjavascript-objects

Static async function in JavaScript class


I'm having trouble with a static async method on a JavaScript class. If I remove the static keyword it works fine to call within the class but then I won't be able to call it by using the class.

My desired outcome is to use the exist method on the class itself using User.exist(email) and on an instance of the class, e.g. foo.exist(email).

Where do I think wrong?

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

Solution

  • When you define the method of a class as static member, it is not available on instance using this keyword. You can directly call it using the class name inside class functions like 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