You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决将Promisified MySQL查询结果传入Inquirer choices的Pending问题

解决MySQL promisify后获取查询结果的问题

你的核心问题出在对promisify后的query函数使用方式错误,以及异步结果的处理逻辑不对,以下是修正方案:

错误原因拆解

  1. promisify后的query不需要回调:你给await query(...)传了回调函数,但promisify的作用就是把回调式API转成Promise API,回调里的结果无法被外部的async函数捕获。
  2. getAllRoles没有返回值:你的函数里处理了结果但没return,导致调用getAllRoles().then(...)时拿到的是undefined。
  3. 直接打印未完成的Promise:const roles = getAllRoles().then(...)本身还是Promise,同步代码里直接console.log会显示pending状态。

修正后的代码

第一步:修复getAllRoles函数

const getAllRoles = async () => {
  try {
    // promisify后的query直接await获取结果,无需回调
    const results = await query(`SELECT title AS 'Job Title' FROM role;`);
    // 提取职位名称并返回数组
    return results.map(item => item['Job Title']);
  } catch (err) {
    console.error('查询角色失败:', err);
    throw err; // 抛出错误让调用者处理,或者返回空数组[]
  }
};

第二步:正确获取结果并用于Inquirer

方式一:用async/await(推荐,代码更清晰)

// 把逻辑放在async函数里执行
async function startApp() {
  try {
    const roles = await getAllRoles();
    // 此时roles就是处理好的职位名称数组,直接传给Inquirer
    const selectedRole = await inquirer.prompt([
      {
        type: 'list',
        name: 'role',
        message: '请选择职位:',
        choices: roles
      }
    ]);
    console.log('你选择的职位是:', selectedRole.role);
  } catch (err) {
    console.error('程序出错:', err);
  }
}

// 启动程序
startApp();

方式二:用then链式调用

getAllRoles()
  .then(roles => {
    return inquirer.prompt([
      {
        type: 'list',
        name: 'role',
        message: '请选择职位:',
        choices: roles
      }
    ]);
  })
  .then(selectedRole => {
    console.log('你选择的职位是:', selectedRole.role);
  })
  .catch(err => {
    console.error('程序出错:', err);
  });

内容的提问来源于stack exchange,提问作者DSwecker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 14:45:35