I have a function that gets users emails given an array of roles ids and a given course id. I am trying to return that array containing all the users but the return is happening before SQL select. So it appear the array never gets populated.
Below is my function:
function getUsersWithRoles(roles, course_id) {
let arr = [];
roles = roles.split(',');
// MySQL connection func
connect((con) => {
let query = `select * from roles join users on users.id = roles.users_id where roles.id in(${roles.join(',')}) and roles.course_id = ?`;
let values = [course_id];
try {
con.query(query, values, (error, result, fields) => {
if (error) {
throw err;
}else {
result.foreach((user) => {
arr.push(user);
// I am only able to access the pushed users here ...
});
}
})
}catch(err) {
console.log(err)
}
});
// This runs before my connection so it returns empty array :(
return arr;
}
If it helps, below is the function I use that makes my SQL connection
module.exports = (cb) => {
try {
// try to establish connection w/ info from .env
var con = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE
});
}catch (err) {
console.log(`ERROR: connect: mysql.createConnection(): ${err}`);
}
con.connect((err) => {
if (err) {
console.log(`ERROR: connect: con.connect(): ${err}`);
}else {
try {
cb(con);
}catch (err) {
console.log(`ERROR: connect: cb(con): ${err}`);
}
setTimeout(() => {
// Close the connection after an allotted time
try {
con.end();
}catch (err) {
console.log(`ERROR: connect: con.end(): ${err}`);
}
}, 60 * 1000);
}
});
}
Thanks in advance!!