将variables传入callback函数
我有这样一段代码:
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 } }
为了避免callback地狱,我给callback函数一个名字和重构它如下:
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创build的连接
现在我的问题是,我不能在checkExistence()
引用guid,我不想让guid
成为一个全局variables。
是否有可能在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));
也许你可以使用绑定function,
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));