How can I pass scope to a callback in node-mysql?

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

稿源:Node.js Recipes (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 后端存储 » How can I pass scope to a callback in node-mysql?

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录