Search code examples
mysqlnode.jsasynchronousnode-mysql

NodeJS Async with mysql is confusing me


I am new to NodeJS. I have the following snippet.

var connection = mysql.createConnection(dbConfig);

connection.connect(function(err) {
    if (err)
        console.log("MySQL Connection Error: ", err);
    else
        console.log("Connection successfully established");

});

connection.query("SELECT * FROM `members1617`;",function(err,rows) {
    if (err)
        console.log("err: ", err);
    else
        console.log("rows: ",rows);

    connection.end();
});

Is this bad code? I think it is because there is no guarantee that connection.connect() is finished and the connection has been established before the query is activated. And id the query is esecuted before the connection is made then there will be all sorts of errors. How is the Async working here?


Solution

  • I would recommend that you use knex, a simple query builder wrapper for the popular node-mysql library.

    After initializing knex you are given an object is a connection pool to your database. That object can have functions chained off of it to perform queries. Queries will return promises and will only be executed when a connection has been properly made. Knex does this for you automatically.

    Your code would look like:

    function getMembers(){
      return knex.select().from('members1617')
         .then(rows => return rows)
         .catch(err => console.log(err))
    }
    

    It's as simple as that.

    I would also recommend that you use a promise library such as Bluebird so that you can properly handle promises and promise chains.

    Please note: Regardless of whether or not you choose to use knex or node-mysql, I would highly recommend that you learn how to either use promises or generators to handle asyncronous control flow in Node. There are several tutorials and blogs at your disposal.