-2

I have a class let's suppose A and it has two function AA and BB as follow.

export class A {
    constructor(){}

    public async AA(X){
     return true;
    }

    public async BB(){
       var users=new Users({      // db model
         name: 'test'
       });

       users.save(function(err,data){
         if(err){
           console.log(err);
         }else{
            var result = await this.AA(data);   // Cannot read property 'AA' of null
         }
       });
    }

}

I am not sure how can i access or make public function AA available inside callback function.

I am getting error: TypeError: Cannot read property 'addRecipient' of null

Jitendra
  • 3,135
  • 2
  • 26
  • 42
  • Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Dexygen Nov 03 '18 at 11:53

1 Answers1

2

1) it seems you assigned the User class instance to the users variable.

but here, you are making use of user instead of users

2) The Issue is with this operation user.save(function(err,data){ if(err){ console.log(err); }else{ var result = await this.AA(data); // Cannot read property 'AA' of null } });

this keyword within a function has a different scope to the global this within the class

if you can, convert the function to an arrow function

user.save((err,data) => {
     if(err){
       console.log(err);
     }else{
        var result = await this.AA(data);   // 
Cannot read property 'AA' of null
     }
   });

or you can pass the global scope has a variable, then make use of it.

var self = this;
user.save(function(err,data){
     if(err){
       console.log(err);
     }else{
        var result = await self.AA(data);   // 
Cannot read property 'AA' of null
     }
   });
Triple0t
  • 444
  • 3
  • 9
  • 1) By mistake i have used user instead of users. (I edited it) 2) Great, @SeunBincom Both of you solution works well. – Jitendra Nov 03 '18 at 12:39