简体   繁体   中英

Node.js connection to mysql database callback functions not executed

I'm trying to connect my node.js application to a mySQL database, but it seems like the callback functions of con.connect() and con.query() are not executed. This is the connection part of my code:

const mysql = require('mysql');
const con = mysql.createConnection({
           host: "localhost",
           user: "user",
           password: "pass",
           database: "db",

    });

app.get('/timetracking/dbTest', (req, res) => {
    var error1;
    var r;



    con.connect(function(err){
        s = 3;
        res.send(err);
    });

    var s = 1;

    con.query("SELECT * FROM Employee", function (err, result, fields) {
        error1 = err;
        res.send("yes");
        r = result;
        s = 2;
    });
    if (error1) res.send(error1 + "fail");
    else res.send(r + "ok" + s);
});

The App is starting normally and I can view the site in my browser, but the result I get is "undefinedok1". That means that the value of the send variables don't get changed in the callback functions. The mysql module is installed. Furthermore, I'm getting no error messages if I enter eg a invalid password for the DB user. I cant imagine why they don't get changed.

The callback code runs asynchronously from the rest of your method. You need to run the code in each successive callback, or use async/await or promises.

The simplest adjustment with your existing code (freehanded, may have syntax errors):

app.get('/timetracking/dbTest', (req, res) => {
    var error1;
    var r;

    con.connect(function(err){
        s = 3;
        if (err) {
          return res.send(err);
        }

        var s = 1;

        con.query("SELECT * FROM Employee", function (err, result, fields) {
            error1 = err;

            r = result;
            s = 2;

            if (error1) res.send(error1 + "fail");
            else res.send(r + "ok" + s);
        });
    });
});

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