0

I don't know javascript very well. 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 query rows from inside of function? How can I define a global variable?

1
  • 2
    This is not a problem with global variable definition, but trying to use asynchronous methods in a synchronous way. That's not possible. I've written an analogy, perhaps it helps you with understanding it: stackoverflow.com/a/11689804/938089 Commented Dec 2, 2012 at 11:43

1 Answer 1

1

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

how would u return the value?
You can't. That's not how you do asynchronous programming.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.