如何从回调函数中修改全局变量。在 node.js

How can i modify a global variable from within a callback function . in node.js

在 node.js 中,我想将 mysql 查询的结果存储在全局变量中,以便我可以将其导出或将其记录到控制台,但似乎全局变量不是从回调函数内部修改的,那么能做什么呢?请帮忙,tgis 是我的简单代码

    var mysql = require("mysql");
var text = "begin : ";
var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "ajax",
});
con.connect(function (err) {
  if (err) throw err;

  var sql = "SELECT * FROM `nom`";
  con.query(sql, function (err, result) {
    if (err) throw err;

    result.forEach((row) => {
      text +=
        "  the first is : " +
        row.first +
        " and the second is : " +
        row.second +
        "\n";
    });
  });
  con.end();
});

console.log(text);

您当前的代码不是完全同步的,即第 1 行、第 2 行和第 3 行可能作为第 1 行、第 3 行、第 2 行执行。您的代码是异步的,因为您调用了 con.connect,它使用回调(即它会在尝试连接到您的 mysql 数据库时调用您提供的函数)。如果您想在连接后打印文本,不建议使用全局变量或更准确地说是在代码末尾使用 console.log(text);,因为 console.log(text); 可能 运行在 con.connect 尝试连接到您的数据库之前。因此,以下是针对此特定示例的一项建议:

var mysql = require("mysql");
var text = "begin : ";
var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "ajax",
});
con.connect(function (err) {
  if (err) throw err;

  var sql = "SELECT * FROM `nom`";
  con.query(sql, function (err, result) {
    if (err) throw err;

    result.forEach((row) => {
      text +=
        "  the first is : " +
        row.first +
        " and the second is : " +
        row.second +
        "\n";
    });
    console.log(text); 
    //write code to export to file/remote service here
  });
  con.end();
});


Javascript Function Scope 是我链接到的另一个特殊兴趣,并且有许多资源可以描述和探索它。建议在您未来的代码中,特别是因为您正在使用异步代码,您尝试本地化或在您的函数范围内工作,并避免使用将在不同时间由不同函数修改的全局变量,这可能难以预测和因此会认为您的project/code“不可预测”。