简体   繁体   中英

Call async function in other function

I am having a problem with asynchronous functions. I have the following function which works fine and basically searches into the firebase realtime database for a matching username:

  static async getSnapshot(fc: FormControl){
    let isPresent:boolean = false;
    await firebase.database().ref().child("users").orderByChild("username")
    .equalTo(fc.value)
    .once("value", snapshot => {          
    }).then((data)=> {
      if(data.exists())
        isPresent = true;
      else
        isPresent = false;
    });
    console.log(isPresent);
    return isPresent; 
  }

The problem is when I call this function in another where I want to do other operations based on the result:

  static async validUsername(fc: FormControl){
    try{
      let bool:boolean =await this.getSnapshot(fc.value)
      if(bool===true)
         return  ({validUsername: true});         
      else{
         return (null); 
       } 
      }catch(e){
        console.log(e)
      }         
  }   

The line:

let bool:boolean =await this.getSnapshot(fc.value)

returns the following error:

TypeError: Cannot read property 'getSnapshot' of undefined

How can I modify my function? Thanks in advance for response

this refers to an instance usually. Static methods don't belong to any instance so this doesn't make sense in them.

To fix your case, just use your class name instead of this . Eg

   class APIHandlers {
      static async getSnapshot {...}

      static async validUsername(fc: FormControl){
          try{
            let bool:boolean = await APIHandlers.getSnapshot(fc.value);
          ...
       } 
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM