I'm building a small reporting tool with Node.js and I am facing some scoping problems with Javascript. I am calling a function and it should return a array with cities from a database query. Here the function.
function queryBuilderZone () {
var includedCities = new Array();
q = heredoc(function(){/*
SELECT majlis.MajlisId
FROM majlis
WHERE majlis.ZoneId = -ZONE-
*/});
q = q.replace(/-ZONE-/g, inZone);
connection.query(q, function(err, rows, fields) {
if (err) throw err;
var rowsLentgh = rows.length;
for (var i = 0; i < rowsLentgh; i++) {
includedCities.unshift(rows[i].MajlisId);
};
console.log(includedCities); // <-- output correct: ['...', '....']
});
connection.end();
console.log(includedCities); // <-- output wrong: []
return includedCities;
}
This is my call from the main program
includedCities = queryBuilderZone();
console.log(includedCities); // <-- output wrong: []
Where is the problem and why is this function not returning the elements in the array includedCities
?
And in the scope of connection.query
it shows the correct and expected value.
By the way I am using the mysql
module for building the query and replacing the placeholder in the query.