CodeFoodPixels / node-promise-mysql

A wrapper for mysqljs/mysql that wraps function calls with Bluebird promises.
MIT License
338 stars 63 forks source link

Cannot read property 'query' of undefined #7

Closed christiannwamba closed 8 years ago

christiannwamba commented 8 years ago

I am sorry to be the first that is starting an open issue. My implementation returns Cannot read property 'query' of undefined error

var con;
mysql.createConnection({
    host: config.db.host,
    user: config.db.username,
    password: config.db.password,
    database: config.db.database
}).then(function(connection){
    con = connection;
});

con.query(queries.allUsers).then(function (err, users) {
    console.log(users);
});

What could I have done better?

christiannwamba commented 8 years ago

The below snippet worked though. Maybe there is something about Promises or JavaScript that I am missing

var con;
con = mysql.createConnection({
    host: config.db.host,
    user: config.db.username,
    password: config.db.password,
    database: config.db.database
}).then(function (connection) {
    return connection;
});
con.then(function (connection) {
    connection.query(queries.allUsers).then(function (users) {
        console.log(users);
    });
});
CodeFoodPixels commented 8 years ago

In your first example, con is undefined because it's assignment is being done asynchronously, so when it makes the call to createConnection(), it carries on to con.query() without having assigned con.

In your second example, it works because con is a promise so after it's called createConnection() it waits for con to be resolved before continuing.

I'm going to close this issue because it's not an issue with the module.

christiannwamba commented 8 years ago

@lukeb-uk One more thing. I just replicated the example in your docs while trying to get acquainted with the module. Does it mean the doc examples are wrong?

CodeFoodPixels commented 8 years ago

The doc examples aren't wrong, but they probably aren't the best for those unfamiliar with promises. I'll have a look at clarifying them.

christiannwamba commented 8 years ago

@lukeb-uk Ok. We call it a day then...