简体   繁体   中英

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

In node.js , and i wanna store the result of a mysql query in a global variable so i can export it or log it to the console whatever , but it seems that the global variable is not modified from within the callback function , so what can do ? pleaase help , tgis is my simple code

    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);

Your current code is not entirely synchronous ie line 1, line 2 and line 3 may execute as line 1, line 3, line 2. Your code is asynchronous because you have a call to con.connect which uses callbacks (ie it will call the function you provided when it has attempted to conenct to your mysql db). If you would like to print the text after the connection it would not be recommended to use a global variable or more precisely have your console.log(text); at the end of your code since the console.log(text); may run before con.connect has attempted to connect to your database. The following is therefore one recommendation for this specific example:

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 is another peculiar interest which I have linked to and many resources are available which describe and explore this. It is recommended that in your future code, especially since you are working with asynchronous code that you try to localize or work within your function scope and avoid using global variables that will be modified by different functions at different times which can be difficult to predict and will therefore consider your project/code "unpredictable".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM