0

I have the following code:

app.get('/', async function (req, res) {

    const mysql = require("mysql");

    // Connection to db
    const connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'PASSWORD',
        database: 'test_database'
    });

    await connection.connect(function(err){
        if (err){
            return console.error("error: " + err.message);
        }

        console.log("Connected to test_database");
    });


    // DO FIRST QUERY
    console.log("About to do first query")
    let search_term = "1";
    let query = "SELECT * FROM main WHERE id = \'" + search_term + "\'";
    let firstResult;
    firstResult = await connection.query(query, (err, results) => {
        if (err) return console.error(err);

        console.log(JSON.stringify(results));
        console.log(JSON.stringify(results[0]));
        console.log(JSON.stringify(results[0]["MiddleName"]));

        closeConnection(connection);

        return JSON.stringify(results[0]["MiddleName"]);
    });

    console.log("First result: " + firstResult);

});


const server = app.listen(5000, function () {
    console.log('Server is running on port 5000');
});


let closeConnection = async function(connection){
    await connection.end(function (err){
        if (err){
            return console.log("Error: " + err.message);
        }

        return console.log("Database connection closed");
    })
}

And when I run it using node hometest I get this as the output:

Server is running on port 5000
About to do first query
First result: [object Object]
Connected to test_database
[{"id":1,"FirstName":"firstName","MiddleName":"middleName","LastName":"lastName"}]
{"id":1,"FirstName":"firstName","MiddleName":"middleName","LastName":"lastName"}
"middleName"
Database connection closed

So I think I have a race condition issue. console.log("First result: " + firstResult); is being run before firstResult is defined (It is definintely not defined as when I try to print the JSON.stringified() version I get a UnhandledPromiseRejectionWarning). I am not sure why though as connection.query() has the await before it. Any help would be much appreciated as I have spent wayyyyy too long trying to figure this out as I want to use the result from one query as the input for the next and so on (Including ones with multiple results so just doing it all inside the callback becomes unsuitable very quickly)

ArchieV
  • 13
  • 1
  • 1

0 Answers0