I'm using a function to collect data from multiple MySQL tables to build an array that will be returned. I'm not sure why but when I go to return the below code I get undefined
although when I use console.log
all the data displays correctly? I'm not sure if this is due to the return statement being faster than the MySQL statements but I would've presumed that Node would wait till all the SQL Statements had completed before returning? Any suggestions would be awesome.
function testfunction(){
let variable = "false",
variable2 = "false";
connection.query("SELECT COUNT(*) AS rowCount FROM `users`;",[], function (error, rows, fields) {
if (error) {console.log(error);}
let users = rows[0].rowCount;
connection.query("SELECT COUNT(*) AS rowCount FROM `towns`",[], function (error, rows, fields) {
if (error) {console.log(error);}
let towns = rows[0].rowCount;
let array = {
"data":{
"users":users,
"towns":towns,
"variable1":variable,
"variable2":variable2
}
};
console.log(array)
return array;
});
});
};
Output:
return output
undefined
console.log output
{ data:
{ towns: 1, users: 1, variable1: 'false', variable2: 'false' } }
Thanks in advance for the help, this isn't a problem I've ran into before and I'm eager to learn what I'm doing wrong :)