node.js global variable problemetical

Actually, i don't know javascript very well. So, i can't define a global variable.

var data = 'empty';

connection.query('SELECT * FROM deneme',function(err, rows, fields){
    if (err) throw err;
    data = rows;
});

console.log(data);

Normally, console need to return rows' data but It returns 'empty'. How can i quarry rows from inside of function, Shortly, how can i define global variable?

The reason it is not working is because you console.log is outside the asynchronous code block. Basically what is happening is this:

  1. data is set to empty;
  2. connection issues a database request;
  3. console.log fires ( data is empty at that point );
  4. database response is received;
  5. callback fires;
  6. data is set to rows.

So in order to get what you want simply put console.log statement inside an asynchronous block code:

var data = 'empty';

connection.query('SELECT * FROM deneme',function(err, rows, fields){
    if (err) throw err;
    data = rows;
    console.log(data);
});