0

When I am trying to get an array through this function:

function getdata() {
    var messages=[];
    var query=connection.query('SELECT * FROM chat', function(err,rows,fields) {
        messages=rows;
    });
    return messages;
}

console.log(getdata()); // I get []

But anytime the result is [] but if I insert a console.log(rows) in the function, I have all my data.

So how can I do for the function to wait getting the data before returning messages?

EDIT,: I resolved the problem using async function

lopata
  • 1,325
  • 1
  • 10
  • 23
  • 1
    asynchronous requests - you need to handle this instead of checking the result immediately.. – amdixon May 31 '15 at 11:15
  • Of course. You are calling an async function. Which will run AFTER your return statement, in a different context. Use Google and read about asynchronous Javascript, it seems you are missing fundamental concepts. – Mörre May 31 '15 at 11:15
  • Can someone tell me how to transform this in asynchronous function? (I don't use jquery, since it's on a node.js server) – lopata May 31 '15 at 11:37

0 Answers0