将变量传递到回调函数中
Passing variables into callback function
我有一段这样的代码:
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
}
}
为了避免回调地狱,我给回调函数起一个名字,并重构如下:
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
是从node-mysql创建的连接
现在我的问题是我不能在checkExistence()
中引用 guid,并且我不想guid
作为全局变量。
有可能在checkExistence()
获得guid
吗?
可以将 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));
你可以使用 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));
也许你可以使用绑定函数,
var checkExistence = function(guid, err, rows) { ...
并像这样调用方法查询
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));
相关文章:
- JavaScript回调函数
- 如何在回调函数中执行流
- 回调函数中传递参数的困难(Google Map API Markers)
- 如何正确地将参数传递给RequireJS回调函数
- 回调函数在python代码中离线
- 从AJAX回调函数中分离数据
- 赋值后的回调函数
- 如何在javascript回调函数中返回多个变量
- 函数表达式,返回回调函数
- 等待回调函数执行
- JavaScript回调函数和Google Feed API
- 如何从ajax成功回调函数中读取javascript变量
- 正在保存JavaScript内部回调函数中的值
- 有没有什么方法可以停止Jquery中的animate(也可以停止完整的回调函数)
- 如何在javascript中添加带有回调函数的按钮点击事件作为window.conf
- 在Golang回调函数中启用CORS
- 在初始函数完成之前调用回调函数
- jQuery Mobile:如何在$.Mobile.changePage之前运行回调函数
- 即使使用回调函数也无法返回值
- 为什么prototypjs观察到回调函数有绑定