Havesting mysql queries with node

I just started with Node.js and I am stuck at how to harvest the result of a database query with node.

If we considering how this work in PHP we have something like:

(after setting the connection $connection)
$query="select field_x from Table where field='something'";
$result=@ mysqli_query($connection, $query);
if(mysqli_num_rows($result)>0)
{
   $row=@ mysqli_fetch_array($result);
}
$data='';
if(isset($row['field_x']))
{
   // query result is HARVESTED
   $data=$row['field_x'];
}

and if the result of the query is not null, $data (=$row['field_x']) can be used every where in the code out of the query block.

Is there a very simple and straight forward way (analogous to PHP way) to do this in node.

Basically I would like to define an arrray/variable with global scope and pass it to the connection-query block and put in that array/variable the result of the query, something like:

var Array=[]; // global scope
var mysql = require('mysql');
var connection = mysql.createConnection({some_stuff});

connection.connect();
var queryString = 'SELECT field_x FROM Table';
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;

for (var i in rows) {
    Array.push(rows[i].field_x));
}
});

connection.end();

Any suggestion/advice?

Regards.

It looks like you're ending the connection before the query is done running & responding. Try putting connection.end() inside the callback.

I am feeling a bit silly answering my own question... Anyway.

My question is about if there is a similar approach as in PHP to harvest data from a database. The thing is that since PHP is not asynchronous, querying a database takes place in the normal executing flow, which means that one has to wait till the database server responses before executing the next line of code. In the asynchronous world of node.js, querying a database involves callbacks, these callbacks are out of the synchronous execution flow.

Therefore, in this case, trying to implement an analogous of the PHP code will fail because any reference to the array where the result of the database query means to be set, happens synchronously while querying the database is an asynchronous task, which mean that it will be execute at some point after the synchronous flow has finish execution.