static async funcion in javascript class

Viewed 2498

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 itselt using User.exist(email) and on an instance of the class ex. 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
2 Answers

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 

You need to call your static function in a static context, so User.exist() instead of 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

Related