Hello
I am a beginner and struggling with the asynchronous nature of Node.js,
could you please give me a hint how to deal with following issue.
In my test code below, I do an SQL query. I will get callbacks for each result and I will then add counter value and store the result into an array.
This all works fine because I am inside "this query process namespace" or whatever.
After the query is over, I will print out the array and the counter. They are both undefined! This I assume comes from the fact that inside my callbacks the process and environment was different. I have few questions: first one is, am I right with my assumptions that its not possible to get "stored" the parameter values somehow inside the callbacks to be used later outside the callbacks?
Should I try to handle and finish the whole operation inside the query callback, so that I dont even have to try to store these values outside this scope?? Any help and hints are very welcome :-)
function readDB() {
var counter = 0;
var testArray = new array();
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'TestDB'
});
connection.connect();
var query = connection.query('SELECT * from Users');
query.on('error', function(err) {
throw err;
});
query.on('fields', function(fields) {
});
query.on('result', function(row) {
counter += 1;
testArray[counter] = row;
console.log("testArray: " + testArray);
});
connection.end();
console.log("testArray: " + testArray + ", counter: " + counter);
}