[英]Passing variables into callback function
I have a piece of code like this: 我有一段这样的代码:
var guid = 'unique_guid';
con.query('SELECT guid FROM myDB.myTable WHERE guid = ?', guid, function(err, rows) {
if(err) throw err;
if(rows.length == 0) {
console.log('new guid: ' + guid);
// do more things which require guid
} else {
console.log('old guid: ' + guid);
// do more things which require guid
}
}
In order to avoid callback hell, I give the call back function a name and refactor it as the following: 为了避免回调地狱,我给回调函数起一个名称,并按以下方式对其进行重构:
var checkExistence = function(err, rows) {
if(err) throw err;
if(rows.length == 0) {
console.log('new guid: ' + guid); // guid can't be referenced here
// do more things which require guid
} else {
console.log('old guid: ' + guid); // guid can't be referenced here
// do more things which require guid
}
}
con.query('SELECT guid FROM myDB.myTable WHERE guid = ?', guid, checkExistence);
con
is a connection created from node-mysql con
是从node-mysql创建的连接
Now my problem is that I can't reference guid in checkExistence()
, and I don't want to make guid
as a global variable. 现在我的问题是我无法在checkExistence()
引用guid,并且我不想将guid
为全局变量。
Is it possible to get guid
in checkExistence()
? 是否可以在checkExistence()
获得guid
?
You can add guid as parameter and return a function: 您可以添加guid作为参数并返回一个函数:
var checkExistence = function(guid) {
return function(err, rows) {
if(err) throw err;
if(rows.length == 0) {
console.log('new guid: ' + guid); // guid can't be referenced here
// do more things which require guid
} else {
console.log('old guid: ' + guid); // guid can't be referenced here
// do more things which require guid
}
};
};
con.query('SELECT guid FROM myDB.myTable WHERE guid = ?', guid, checkExistence(guid));
You can use Function.bind function for thet, like this: 您可以为这些使用Function.bind函数,如下所示:
var checkExistence = function(guid, err, rows) {
if(err) throw err;
if(rows.length == 0) {
console.log('new guid: ' + guid); // guid can't be referenced here
// do more things which require guid
} else {
console.log('old guid: ' + guid); // guid can't be referenced here
// do more things which require guid
}
}
con.query('SELECT guid FROM myDB.myTable WHERE guid = ?', guid, checkExistence.bind(null, guid));
Maybe you could use the bind function, 也许您可以使用bind函数,
var checkExistence = function(guid, err, rows) { ...
and call the method query like this 然后像这样调用方法查询
con.query('SELECT guid FROM myDB.myTable WHERE guid = ?', guid, checkExistence.bind(null, guid);
var checkExistence = function(err, rows, guid) {
if(err) throw err;
if(rows.length == 0) {
console.log('new guid: ' + guid); // guid can't be referenced here
// do more things which require guid
} else {
console.log('old guid: ' + guid); // guid can't be referenced here
// do more things which require guid
}
}
con.query('SELECT guid FROM myDB.myTable WHERE guid = ?', guid, checkExistence(err, rows, guid));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.