I am having an issue with accessing a promise from a function containing multiple MySQL queries. I need to ask multiple questions and need the answer choices to update dynamically from what is currently in the DB (this is working).
I need to pass the empId variable to the final query but am getting an error that "empID is not defined". When I console.log "employee" and "newrole" I receive objects { whichemp: '1 Eric Scott' } { newrole: '1 Senior Engineer' }
I've tried all I could think of but am hitting a wall. I appreciate any feedback.
function empUpRole() {
connection.query("SELECT * FROM employee", (err, res) => {
if (err) throw err;
inquirer.prompt([
{
type: "list",
message: "Which employee's role would you like to update?",
name: "whichemp",
choices: res.map(res => res.id + " " + res.first_name + " " + res.last_name)
}
]).then(employee => {
let empId = employee.id
connection.query("SELECT * FROM role", (err, res) => {
if (err) throw err;
inquirer.prompt([
{
type: "list",
message: "What is the employee's new role?",
name: "newrole",
choices: res.map(res => res.id + " " + res.title)
}
]).then(newrole => {
let roleId = newrole.id
console.log(employee, newrole)
let query = connection.query("UPDATE employee SET role_id = ? WHERE id = ?",
[roleId, empID],
(err, res) => {
if (err) throw err;
}
);
start();
});
});
});
});
Solution:
function empUpRole() {
connection.query("SELECT * FROM employee", (err, res) => {
if (err) throw err;
inquirer.prompt([
{
type: "list",
message: "Which employee's role would you like to update?",
name: "whichemp",
choices: res.map(res => res.id + " " + res.first_name + " " + res.last_name)
}
]).then(employee => {
let empId = employee.whichemp.split(' ')[0];
connection.query("SELECT * FROM role", (err, res) => {
if (err) throw err;
inquirer.prompt([
{
type: "list",
message: "What is the employee's new role?",
name: "newrole",
choices: res.map(res => res.id + " " + res.title)
}
]).then(newrole => {
let roleId = newrole.newrole.split(' ')[0];
console.log(empId, roleId)
console.log(employee, newrole)
console.log(newrole.id, employee.id)
let query = connection.query("UPDATE employee SET role_id = ? WHERE id = ?",
[roleId, empId],
(err, res) => {
if (err) throw err;
}
);
start();
});
});
});
});