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

使用promise-mysql返回undefined,如何让函数等待查询结果?

如何让函数等待MySQL查询结果返回?

嘿,我碰到过一模一样的问题!这本质是异步操作没正确处理导致的——MySQL查询是异步任务,你的getKey函数没等查询完成就返回了,所以调用时拿到的是undefined。既然你用了promise-mysql(基于Promise的库),咱们可以用两种方式解决:

方法1:用async/await让代码“同步化”

这是最直观的写法,把getKey改成异步函数,用await等待数据库连接和查询完成:

const mysql = require('promise-mysql');
const dbConnect = require('../connection'); // 你的数据库连接配置

async function getKey(keyName) {
  let connection;
  try {
    // 等待数据库连接建立
    connection = await mysql.createConnection(dbConnect);
    // 等待查询结果返回,解构拿到行数据
    const [rows] = await connection.query('SELECT value FROM your_table WHERE `key` = ?', [keyName]);
    // 有结果就返回对应value,没有返回null
    return rows.length > 0 ? rows[0].value : null;
  } catch (err) {
    console.error('查询出错:', err);
    throw err; // 抛出错误让调用方处理
  } finally {
    // 不管成功失败,都关闭连接避免资源泄漏
    if (connection) await connection.end();
  }
}

// 调用的时候也要用async/await(或者.then())
async function fetchAndUseKey() {
  try {
    const value = await getKey("tc_api_user_key");
    console.log('拿到的value:', value); // 现在就能拿到正确结果了!
  } catch (err) {
    console.error('获取key失败:', err);
  }
}

fetchAndUseKey();

方法2:用Promise链式调用(不用async/await)

如果你更习惯传统的Promise写法,也可以用.then()链式处理异步流程:

const mysql = require('promise-mysql');
const dbConnect = require('../connection');

function getKey(keyName) {
  return mysql.createConnection(dbConnect)
    .then(connection => {
      return connection.query('SELECT value FROM your_table WHERE `key` = ?', [keyName])
        .then(rows => {
          connection.end();
          return rows.length > 0 ? rows[0].value : null;
        })
        .catch(err => {
          connection.end();
          throw err; // 传递错误
        });
    })
    .catch(err => {
      console.error('连接/查询出错:', err);
      throw err;
    });
}

// 调用时用.then()处理结果
getKey("tc_api_user_key")
  .then(value => {
    console.log('拿到的value:', value);
  })
  .catch(err => {
    console.error('获取失败:', err);
  });

关键提醒

  • 异步操作必须等待其完成才能拿到结果,不能像同步代码那样直接返回
  • 一定要处理错误(try/catch或者.catch()),避免隐藏bug
  • 记得关闭数据库连接,不然会造成连接泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:00:13