0

我正在尝试提取 SQL 查询结果并在查询器提示中填充选择。当控制台记录“选择”时,它会显示来自被调用的 SQL 查询的对象数组,但是当调用inquirer.prompt 并使用查询响应填充选择时,呈现给用户的选择显示为“未定义”。不完全确定发生了什么,因为我有一个几乎相同的功能可以完美运行。

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);
        });
    });
}
4

1 回答 1

0

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!

于 2020-11-05T19:39:48.940 回答