I have a nodejs project that uses inquirer as well as mysql2. I created a class to store my sql queries as functions to be able to use those with inquirer. When I run the following function, I get undefined when I am returning the managers array. But when I console.log the array, everything displays as expected. This is my function:
viewManagers() {
const sql = `SELECT CONCAT(first_name, ' ', last_name) AS manager FROM employee WHERE manager_id IS NULL;`;
db.query(sql, (err, rows) => {
if (err) throw err;
const managers = [];
for (let i = 0; i < rows.length; i++) {
managers.push({ name: rows[i].manager, value: i+1 });
}
managers.push({ name: "None", value: null });
return managers;
});
}
I am calling it like this to test it,
const query = new Query();
console.log(query);
If I change the return statment in the viewManagers function to a console.log(managers); Then the managers array is returned in the console. How can I successfully return this data so it is not undefined? I want to be able to return it and then call this function from within another function. I also tried using promisify and got the same result:
const db = require('../db/connection');
const util = require('util');
const query = util.promisify(db.query).bind(db);
class Query {
async viewManagers() {
try {
const sql = `SELECT CONCAT(first_name, ' ', last_name) AS manager FROM employee WHERE manager_id IS NULL;`;
const rows = await query(sql);
const managers = [];
for (let i = 0; i < rows.length; i++) {
managers.push({ name: rows[i].manager, value: i+1 });
}
managers.push({ name: "None", value: null });
return managers;
} finally {
db.end();
}
}
}
module.exports = Query;