0

I'm asking this simply because I have other similar functions, and those return an array with elements, but I have one that returns an empty array.

In fact, I have 2 other functions that work perfectly, but the third does not. Here are the two that work:

roleQuery = () => {
  const roleArr = [];
  connection.query("SELECT * FROM role", (err, res) => {
    if (err) throw err;
    res.forEach(role => {
      roleArr.push(role.title)
    });
  });
  return roleArr;
};

managerQuery = () => {
  const managerArr = [];
  connection.query('SELECT employee.id, CONCAT(employee.first_name, " ", employee.last_name) AS employee, role.title FROM employee RIGHT JOIN role ON employee.role_id = role.id WHERE role.title = "General Manager" OR role.title = "Assistant Manager" OR role.title = "Sales Lead" OR role.title = "HR Specialist"', (err, res) => {
    if (err) throw err;
    res.forEach(manager => {
      managerArr.push(manager.employee)
    });
  })
  managerArr.unshift("None");
  return managerArr;
};

And they are called in inquirer choices prompts for list types.

Here is the one that returns an empty array:

employeeQuery = () => {
  const employeeArr = [];
  connection.query("SELECT * FROM employee", (err, res) => {
    if (err) throw err;
    res.forEach(employee => {
      let fullName = employee.first_name + " " + employee.last_name;
      employeeArr.push(fullName) 
    });
  });
  return employeeArr;
};

This one is also called into an inquirer list type for choices.

Again, for some reason, this particular one returns an empty array. Does anyone know why this particular one isn't working as well?

Andrew Bautista
  • 153
  • 2
  • 9
  • your array is defined as constant – Popeye Mar 16 '20 at 04:30
  • @Popeye you can push to a const array – Jaromanda X Mar 16 '20 at 04:30
  • 1
    the callback to `connection.query("SELECT * FROM employee", (err, res) => {` is called asynchronously at some unknown time in the future ... by then, you've returned the empty array - because that's how asynchrony works – Jaromanda X Mar 16 '20 at 04:31
  • why the first two work ... no idea ... probably there's something in how they are used that means the array returned is populated in time to be used .... try `return roleArr.slice();` and `return managerArr.slice();` - if that "breaks" your code, then I'm right - it really depends on how and when the result of these functions is used - you haven't shown that part – Jaromanda X Mar 16 '20 at 04:33

0 Answers0