w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
No hint of errors when trying to connect to a database

The error here is you're coding node.js as if it were procedural. It's not.

connection.connect(function(err) {
    if(err) {
        console.log('error when connecting to database:', err);
    }
    console.log('Connected to the database');

    var queryString = 'SELECT * FROM blogs';

    //change from connection to "this" because you're inside the context of
the connection object now
    this.query(queryString, function(err, rows, fields) {
        if (err) throw err;

        for (var i in rows) {
            console.log('Post Titles: ', rows[i].id);
        }
    }); 

});

Node.js uses a series of callbacks that run when a task is completed. So when you want to do something AFTER you're connected to the DB, you run that code inside the callback.

What your code is doing is attempting to connect to the database, then while attempting to connect to the database you're querying a database you're not connected to, and so on and so forth.

For sake of illustrating the principle a little more, node functions use the following general methodology.

//1
myObj.myFunc( function( err , foo , bar ) {
    //A
});

//2
myObj.myOtherFunc( function( err , someVar ) {
    //B
});

1 will always run before 2. A and B may run in either order depending on when 1 and 2 finish executing. A will always run after 1 is done. B will always run after 2 is done.

Hopefully that helps clear things up ;)





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.