I get a client is not defined
error out of the following code:
var mysql = require('mysql'); var conf = { 'database':'database', 'user':'user', 'password':'password' }; function mysqlQuery(mysql, conf, query, callback) { var client = mysql.createClient({ user:conf.user, password:conf.password }); client.query('USE ' + conf.database, function () { client.query(query, callback); }); } mysqlQuery( mysql, conf, 'SELECT * FROM users;', function selectCb(err, results) { if (err) { throw err; } console.log(results); client.end(); } );
How can I pass the client variable to my callback function? I have no control on how the callback function will be called as it is called by the mysql module.
Problem courtesy of: Simon Jodet
Solution
You could
bind
[docs]
client
to callback
. Inside the callback it will be available as this
then:
client.query(query, callback.bind(client))
and
this.end();
You could also pass it as first parameter:
client.query(query, callback.bind(null, client))
or
client.query(query, function(err, results) { callback(client, err, results); });
where callback
is defined as
function selectCb(client, err, results) {..};
Solution courtesy of: Felix Kling