hi i'm newly learning nodejs and connected mysql database now i want to save the result of a select query in a variable of some type but i cant.
var campGround = [];
console.log("Select Statement started....");
con.connect(function(error){
if(!error){
console.log("Connected");
var sql = "select * from campgrounds";
con.query(sql,function(err,result,field){
if (!err) {
// console.log(JSON.parse(result));
for(var i =0;i<result.length;i++)
{
try {
// console.log(result[i]);
setCampground(result[i]);
// campGround.push(result[i]);
} catch (error) {
console.log(error.message);
}
}
}
else{
console.log("Error while selecting record from campground table. ");
}
});
}else{
console.log("Error DataBase Not Connected!!! select statement");
}
});
function setCampground(value){
this.campGround.push(value);
}
console.log("length after execution :: "+campGround.length);
campGround.forEach(function(value){
console.log("Campground array");
console.log(value);
});
when i execute the above code and debug it...the select statement return from the database 3 records...but when i push them into the array ... and print the array nothing happens...please help
i cant find anything that could help me.
Your mysql query call is asynchronous (callback based) and your call to log the
campGroundis outside that callback so that means you are making a call but not waiting for that call to finish. That is the reason your campGround is not printing any thing.You need to move following lines inside the callback where are are handling the error and response. something like this