The correct way to solve this issue is to write console.log
inside the callback. That's what is highly recommended.
Now coming to the part what you want i.e. writing console.log
after con.query
in the same block and also you don't want console.log
in seperate function (this is what I understand from the question and your comments in other answers)
To achieve this you'll have to wrap con.query
in a promise and use await
to wait till the promise resolves.
var button_settings=[];
await new Promise(function(resolve, reject){
con.query("SELECT * from ht_button", function (err, result, fields){
if (err) reject(err)
button_settings.push(result);
resolve()
});
}).catch(function(err){/* handle err */})
console.log(button_settings);
How the only problem is that you can only use await
inside an async
function. So let's wrap the whole in code an async
function
Final code:
async function doStuff(){
var button_settings=[];
await new Promise(function(resolve, reject){
con.query("SELECT * from ht_button", function (err, result, fields){
if (err) reject(err)
button_settings.push(result);
resolve()
});
}).catch(function(err){/* handle err */})
console.log(button_settings);
}
doStuff();
I have not tested this code with actual mysql thing... But I here's a equivalent test :
async function doStuff(){
var button_settings=[];
await new Promise(function(resolve, reject){
setTimeout(function(){
button_settings = ["foobar"];
resolve();
},1000)
});
console.log(button_settings);
}
doStuff();