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

如何在Node.js中将query查询返回值存入变量,打印为undefined如何解决

问题原因

  • 异步执行顺序问题:pool.query 是异步API,回调函数会在数据库查询完成后才执行,你写在最外层的 console.log(customerData) 会在查询请求发出后立刻执行,此时回调还没触发,customerData 还没被赋值。
  • 变量作用域冲突:你在回调函数内部再次用 var customerData = result.rows 声明了同名变量,这个变量是回调函数的局部变量,赋值操作完全不会影响到外层的 customerData 变量。
  • 语法错误:else分支的SQL语句和参数数组之间缺少逗号,会直接触发语法报错。

修复方案

方案1:沿用回调写法,把查验逻辑放到回调内

if( phone === "" ||  phone === null || phone === undefined ) {
  pool.query('SELECT * FROM customers WHERE licensenumber = $1 ',[Licensenumber], (error, result) => {
    if (error) {
      throw error
    }
    const customerData = result.rows;
    // 查验customerData的逻辑直接写在这里
    console.log(customerData);
    res.status(200).json(customerData)
  }) 
} else { 
  // 补全SQL和参数之间的逗号
  pool.query('SELECT * FROM customers WHERE licensenumber = $1 AND phone = $2',
  [Licensenumber,phone], (error, result) => {
    if (error) {
      throw error
    }
    const customerData = result.rows;
    // 查验customerData的逻辑直接写在这里
    console.log(customerData);
    res.status(200).json(customerData)
  })
}

方案2:用async/await写法,逻辑更简洁

首先要确保当前的外层处理函数被async修饰,示例:

// 示例为express框架的路由处理函数
async function yourHandler (req, res) {
  try {
    let customerData
    if( phone === "" ||  phone === null || phone === undefined ) {
      const result = await pool.query('SELECT * FROM customers WHERE licensenumber = $1 ',[Licensenumber])
      customerData = result.rows
    } else {
      const result = await pool.query('SELECT * FROM customers WHERE licensenumber = $1 AND phone = $2',[Licensenumber,phone])
      customerData = result.rows
    }
    // 此处可正常获取到customerData的值
    console.log(customerData)
    res.status(200).json(customerData)
  } catch (error) {
    throw error
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:45:00