user3242861
user3242861

Reputation: 1929

Node js - How access another function in same controller

I have two functions and i can't access from function 2 to function 1. How can i do that?

class firstController
{        
  one(req, res)
  {
     var stamp = request.query("Select 'ALB'+left(newid(),5)+right(newid(),5)+ left(newid(),5)+right(newid(),5) as stamp");
     Promise.all([stamp]).then(function(listOfResults)
     {
      var data = listOfResults[0][0].stamp;
      res.send(data);
     }).catch(function(err)
     {
       // ... query error checks
       console.log(err);
     });
  }
  two(req, res){
    //get the data returned from function 1
    console.log(this.one(req, res));
  }
}
module.exports = firstController;

i have this error:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'getStamp' of undefined

Thank you

Upvotes: 0

Views: 2438

Answers (1)

R. Gulbrandsen
R. Gulbrandsen

Reputation: 3778

Use this to access functions within the same class in ES6. This is quite complex in ES5 and ES6 compared to other languages and I recommend you have a look at it.

class firstController
{        
  one(req, res)
  {
    res.send("hello");
  }

  two(req, res){
     this.one(req, res);
  }
}
module.exports = firstController;

UPDATE To get the data from one into two you'll need to return the result of the Promise like this

one(req, res) {
   var stamp = request.query("Select 'ALB'+left(newid(),5)+right(newid(),5)+    left(newid(),5)+right(newid(),5) as stamp");
   return Promise.all([stamp]).then(function(listOfResults) {
     return listOfResults[0][0].stamp;
   }).catch(function(err) {
     // ... query error checks
     console.log(err);
     return err;
   });
}

two(req, res){
  //get the data returned from function 1
  console.log(this.one(req, res));
}

Only use res.send when you want to return data to the client

Upvotes: 4

Related Questions