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

Node.js调用MySQL查询函数外部返回undefined问题求助

问题原因

这是Node.js异步API调用的典型错误,核心有两点:

  • connection.query是异步执行方法,你调用inquinamento函数时,SQL查询还未完成,回调函数尚未触发,此时不可能拿到查询结果
  • 你写的return rows.livelloInquinamento是回调函数的返回值,只会返回给connection.query方法内部,外层的inquinamento函数本身没有定义返回值,默认返回undefined

另外补充一个细节错误:rows是SQL查询返回的结果数组,就算只有一条数据也需要通过rows[0].livelloInquinamento才能拿到对应字段值,你直接写rows.livelloInquinamento也会取不到值。

修复方案

方案1:回调函数传值

将需要使用查询结果的逻辑封装为回调函数传入:

var inquinamento = function(callback) {
  connection.query('select livelloInquinamento from livInquinamento;', function(err, rows, fields) {
    if (err) return callback(err);
    callback(null, rows[0].livelloInquinamento);
  });
}

// 调用示例
inquinamento(function(err, livelloInquinamento) {
  if (err) throw err;
  // 所有需要用到查询结果的逻辑都要写在这个回调内部
  console.log(livelloInquinamento);
});

方案2:Promise + async/await 写法(更推荐,代码可读性更高)

先把查询逻辑封装为Promise:

var inquinamento = function() {
  return new Promise((resolve, reject) => {
    connection.query('select livelloInquinamento from livInquinamento;', function(err, rows, fields) {
      if (err) return reject(err);
      resolve(rows[0].livelloInquinamento);
    });
  });
}

// 调用示例,需要在async函数内使用await获取结果
async function getInquinamento() {
  try {
    const livello = await inquinamento();
    // 后续可以正常使用livello变量
    console.log(livello);
  } catch (err) {
    console.error('查询出错:', err);
  }
}
getInquinamento();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:36:05