Passing SQL queries into Inquirer Prompt

2.3k views Asked by At

I'm trying to pull in SQL query results and populate choices in inquirer prompt. When console logging 'choices,' it displays an array of objects from the SQL query that is called, but when calling inquirer.prompt and populating choices with the query response, the choices presented to the user show as 'undefined'. Not entirely sure what's going on because I have an almost identical function that works perfectly.

const viewEmployeesByManager = async () => {
    const choices = await employeeDB_CRUD.getManagers();
    console.log(choices);
    return new Promise( (resolve, reject) => {
        inquirer.prompt([
            {
                name: "manager",
                type: "list",
                message: "Please select a department: ",
                choices: choices
            }
        ]).then( ({ manager }) => {
            console.log(manager);
            resolve();
        });
    });
}
const getManagers = () => {
    return new Promise((resolve, reject) => {
        connection.query(`SELECT CONCAT(b.first_name, " ", b.last_name) AS Name 
        FROM employee a LEFT JOIN employee b
        ON a.manager_id = b.id
        WHERE a.manager_id IS NOT NULL;`, (err, res) => {
            if (err) reject(err);
            resolve(res);
        });
    });
}
1

There are 1 answers

0
Queenscript On

Following the documentation on Inquirer,

the object with a type of "list" must also use a key-value pair with choices and an array value. While choices variable console logs an array of objects, it is still actually an await expression, which causes your async function to pause until a Promise is fulfilled/rejected, and to resume execution of the async function after fulfillment.

According to the MozdDocs on the await keyword, "when resumed, the value of the await expression is that of the fulfilled Promise."

This signals that your choices variable will change, thus it would be better to implement the let keyword because it signals that the variable may be reassigned, which it will the promise is fulfilled.

Please try that, and tell me if it works!