使用 mySQL 和 nodejs 传递承诺

Posted

技术标签:

【中文标题】使用 mySQL 和 nodejs 传递承诺【英文标题】:Passing promises with mySQL & nodejs 【发布时间】:2020-11-10 07:08:16 【问题描述】:

我在从包含多个 mysql 查询的函数中访问 Promise 时遇到问题。我需要提出多个问题,并且需要从数据库中当前的内容动态更新答案选择(这正在工作)。

我需要将empId 变量传递给最终查询,但收到“未定义empID”的错误。当我 console.log "employee" 和 "newrole" 我收到对象 whichemp: '1 Eric Scott' newrole: '1 Senior Engineer'

我已经尝试了所有我能想到的,但我碰壁了。感谢您提供任何反馈。

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();
            );
        );
    );
);

解决方案:

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();
                );
            );
        );
    );

【问题讨论】:

【参考方案1】:

您需要将empID 替换为empId。因为您使用的是 empID 变量,并且它不存在。


我认为这个问题是因为查询者返回的选择字符串喜欢$employee.id $employee.first_name $employee.last_name,所以你不能得到employee.id。所以我使用employee.selectedValue.split(' ')[0] 来获取id。

要访问inquirer.prompt(),您应该使用result.xxxx,其中xxxx 是您传递给inquirer.prompt() 的名称。

employee.selectedValue.split(' ')$employee.id $employee.first_name $employee.last_name 拆分为[employee.id, employee.first_name, employee.last_name] 之类的数组,然后我选择索引0 来获取ID。


要了解更多关于查询者的信息,请转到here。或查看此示例。

示例。

const inquirer = require('inquirer');

const main = async () => 
    const result = await inquirer.prompt([
        
            type: 'list',
            message: "Which employee's role would you like to update?",
            name: 'selectedValue',
            choices: [
                'id1 ahmed1 elmetwally1',
                'id2 ahmed2 elmetwally2',
                'id3 ahmed3 elmetwally3',
            ],
        ,
    ]);

    // if you choise 1
    // result will be selectedValue: "id1 ahmed1 elmetwally1"

    // to get id 
    const id = result.selectedValue.split(' ')[0];
    console.log(id)
;

main();

解决方案。

const updateEmployeeRole = async () => 
  // get employees and choice one
  const employees = await connection.query('SELECT * FROM employee');
  console.log( employees );
  const employee = await inquirer.prompt([
    
      type: 'list',
      message: "Which employee's role would you like to update?",
      name: 'selectedValue',
      choices: employees.map(
        employee =>
          `$employee.id $employee.first_name $employee.last_name`,
      ),
    ,
  ]);
  console.log( employee );
  const employeeId = employee.selectedValue.split(' ')[0];

  // get roles and choice one
  const roles = await connection.query('SELECT * FROM role');
  console.log( roles );
  const newRole = inquirer.prompt([
    
      type: 'list',
      message: "What is the employee's new role?",
      name: 'selectedValue',
      choices: roles.map(role => `$role.id $role.title`),
    ,
  ]);
  console.log( newRole );
  const roleId = newRole.selectedValue.split(' ')[0];

  // update employee role
  const updateResult = await connection.query(
    'UPDATE employee SET role_id = ? WHERE id = ?',
    [roleId, employeeId],
  );
  console.log( updateResult );

  return Promise.resolve();
;

updateEmployeeRole()
  .then(() => 
    console.log('updateEmployeeRole() is Done. Now will run start()');
    start();
  )
  .catch(err => 
    console.error('Something Error ',  err );
  );

【讨论】:

谢谢@Ahmed ElMetwally 我已经盯着它太久了。虽然现在我没有收到错误,但表格也没有更新。我 console.logged empId`` and roleId``` 为每个返回 undefined 但承诺仍然是两个对象。有什么想法吗?我很新,感谢您的帮助。 @kinzito17 我更新了我的答案。你能试试然后告诉我结果吗。 感谢@Ahmed ElMetwally!我之前使用过类似的解决方案,但它不起作用我认为这是语法。我使用拆分来适应我的代码,现在一切都很完美。我非常感谢朝着正确方向的推动。我更新了上面的代码以反映答案。

以上是关于使用 mySQL 和 nodejs 传递承诺的主要内容,如果未能解决你的问题,请参考以下文章

NodeJS 不能等待 MySQL 数据库承诺,而是等待其他承诺

如何在 Node js 中承诺一个 mysql 池连接?

何时使用异步 nodejs?

nodejs 中的异步和 Q 承诺

异步 axios 不使用 NODEJS 运行承诺

使用nodejs在Mysql查询中传递数组