0

I need some help with Classes in NodeJS

I have the following Method inside a class:

GetGreetingsReply(Token)
  {
    var greetings;

    console.log("Token: " + Token);

    this.Connection.query('SELECT * FROM FB_Greetings WHERE Token = ?', Token, function(err, rows) 
    {
        if (err) throw err;

        greetings = JSON.stringify(rows);

     });

    //console.log(JSON.stringify(greetings));

    return greetings;

  }

Then inside this method, I make a query to mysql, and inside function(err, rows) I can print the data to console. But when I assign my variable greetings = JSON.stringify(rows); and then return, its null!

So how can I assign result of the query (rows) into a readable variable, or even a Class variable (this.variable = rows)

Thank you in advance!

1 Answers1

0

There are problem in async process so you need to do like bellow: GetGreetingsReply(Token) { var greetings;

console.log("Token: " + Token);

this.Connection.query('SELECT * FROM FB_Greetings WHERE Token = ?', Token, function(err, rows) 
{
    if (err) throw err;

    greetings = JSON.stringify(rows);

   console.log(JSON.stringify(greetings));

   return greetings;
 });

}

or

async function GetGreetingsReply(Token) { var greetings;

console.log("Token: " + Token);

return greetings = await this.Connection.query('SELECT * FROM FB_Greetings WHERE Token = ?', Token, function(err, rows) 
{
    if (err) throw err;

    return greetings = JSON.stringify(rows);

 });

//console.log(JSON.stringify(greetings));

}

Now its return promise so please use .then(function(){}); clause top get data.