Reputation: 583
I am trying to get MySQL to result from the function. At moment I am trying to set results from function to global array, but this doesn't work.
I am not very familiar with NodeJS or Javascript but I think it's a scope issue.
How would one do this in a proper way? Do I need to use async or maybe return results from a function?
This is what I have at moment.
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'xxxx',
port : '3306',
user : 'xxxx',
password : 'xxxx',
database : 'xxxx'
});
var db_members =[];
get_members();
console.log(db_members); //outputs []
function get_members(){
connection.query("SELECT * FROM users", (err, result, fields)=>{
if (err) throw err;
result.forEach(function(row) {
db_members.push(row.username);
});
console.log(db_members); //this works
});
}
Upvotes: 0
Views: 48
Reputation: 10193
connection.query
is async
function so you are not able to get the result synchronously.
It is needed to make get_members
to return Promise
as the return value so to get the result asyncronously when using it..
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'xxxx',
port : '3306',
user : 'xxxx',
password : 'xxxx',
database : 'xxxx'
});
function get_members() {
return new Promise((resolve, reject) => {
connection.query("SELECT * FROM users", (err, result, fields)=>{
if (err) return reject(err);
var db_members = [];
result.forEach(function(row) {
db_members.push(row.username);
});
return resolve(db_members);
});
});
}
get_members()
.then((members) => {
console.log(members); // This will work.
})
.catch((error) => {
console.error(error);
});
Upvotes: 1