2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Do you recommend async.js?
I've not used async myself. The async/await functionality should be coming natively to the javascript language in ES 7. It wouldn't hurt to learn different methods of handling asychronous code, for no reason other than understanding how different libraries you use work. Promises are very prevalent so it'll come back to bite you some day if you gloss over them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.