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

Node.js中如何在MySQL查询结果回调中使用全局变量?

解决MySQL查询回调中使用全局变量的异步问题

Hey there! I see the issue you're running into—let's break this down and fix it.

问题根源:异步执行顺序

Your console.log(arr) runs before the callback function of conn.query gets executed. That's because conn.query is an asynchronous operation: it sends the SQL request to the database and doesn't wait for the response before moving on to the next line of code. By the time the database returns the result and your callback pushes the value to arr, the console.log has already run with an empty array.

解决方案1:把依赖操作放到回调函数内部

The simplest fix is to move any code that depends on the query result inside the callback. This ensures it only runs after the query completes successfully:

var arr = []; 
var sql = "my sql code"; 

conn.query(sql, function(err, result) {
  // 一定要先处理错误!
  if (err) {
    console.error("查询失败:", err);
    return;
  }
  
  arr.push(result[0]); 
  console.log(arr); // 现在能正确显示查询结果了
});

解决方案2:用Promise + async/await 优化代码

If you prefer code that reads more like synchronous logic (which is easier to follow for complex workflows), you can wrap the conn.query call in a Promise and use async/await:

// 把查询操作封装成Promise
function runQuery(sql) {
  return new Promise((resolve, reject) => {
    conn.query(sql, (err, result) => {
      if (err) reject(err);
      else resolve(result);
    });
  });
}

// 使用async函数处理查询逻辑
async function fetchAndStoreData() {
  var arr = [];
  var sql = "my sql code";

  try {
    const result = await runQuery(sql);
    arr.push(result[0]);
    console.log(arr); // 正确输出查询结果
  } catch (err) {
    console.error("获取数据出错:", err);
  }
}

// 调用async函数
fetchAndStoreData();

小提醒:谨慎使用全局变量

While using a global variable works here, try to limit global variables in larger applications. They can lead to unexpected side effects and make your code harder to debug. Instead, consider encapsulating your data within function scopes or classes whenever possible.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:15:02