在Nodejs中获取未定义的variables
我正在使用Node来运行此代码
但是当我运行这个代码得到在get函数中的leadidvariables的未定义的返回:
call = {}; call.hangup = { get: function(isOpen, ami, elastic, validator, growly, mysql, request){ var self = call.hangup; this.isOpen = isOpen; this.ami = ami; this.elastic = elastic; this.validator = validator; this.growly = growly; this.mysql = mysql; this.request = request; if(isOpen) { ami.on('hangup', function(evt){ var cause_status = parseInt(evt.cause); var message = self.causeStatus(cause_status); var channel = evt.channel; var isDAHDI = validator.contains(channel,"DAHDI"); if((isDAHDI)&&(cause_status == 16)) { var mobile = evt.calleridnum; if(validator.isLength(mobile,11)) { if(validator.matches(mobile,/^09/i)) { var txtMessage = ""; var sending = ""; var leadid = self.searching(mobile, mysql, validator); retrun leadid; /// get the undefined !!!! } } } }); }else { console.log("Hangup's Event is OFF !"); } }, searching: function(number, mysql, validator){ this.number = number; this.mysql = mysql; this.validator = validator; var query = "{sql ...}"; mysql.query(query, function(err, rows, fields) { if (err) throw err; if(!validator.isNull(rows)) { return rows[0].leadid; }else { return false; } }); }, }; module.exports = call;
这是我如何在主文件中调用它:
var call = require('./call'); call.hangup.get(true, ami, client, validator, growly, connection, request);
在另一方面,当我在主文件中调用这个函数(search)时
new call.hangup.searching(number, connection, validator);
它工作正常
我该如何解决?
你需要记住JavaScript是asynchronous的。
当searching
被调用时,数据库查询是asynchronous发出的,函数返回,然后数据库会给你一个结果。 换句话说,你的searching
function不会给你的结果
function(err, rows, fields) { if (err) throw err; if(!validator.isNull(rows)) { return rows[0].leadid; }else { return false; } }
如你所愿,
searching: function(number, mysql, validator){ this.number = number; this.mysql = mysql; this.validator = validator; var query = "{sql ...}"; mysql.query(query, function(err, rows, fields) { if (err) throw err; if(!validator.isNull(rows)) { return rows[0].leadid; }else { return false; } }); --- > This is reached at the end of the call and nothing is returned }, };
它不显式返回任何东西,因此undefined
。
您应该使用promises
或通过searching
一个callback函数,当您的数据库查询返回时将被调用。
所以你的解决scheme应该是这样的:
get: function (...){ ... self.searching(mobile, mysql, validator, whatIwantToDoAfterValidation) }, searching: function(number, mysql, validator, callback){ ... mysql.query(..., callback){ if(!validator.isNull(rows)) { callback(rows[0].leadid); }else { callback(false); } } }, whatIwantToDoAfterValidation: function(leadid){ ...do whatever you want with leadid... }
看看jquery's promises
, jquery's promises
做同样的事情。
- Javascript:将对象的对象转换为对象数组
- 随机获取ECONNREFUSED错误
- 为什么Mongoose用_idreplace对象中的键/值对?
- 这是什么意思??? 当我使用strongloop控制器API时,Vanilla Node.js I / O阻塞会清除吗?
- illegal_argument_exception:没有为字段find映射
- 如何从ModelA.js中调用ModelB.js的方法?
- 在午夜重置variables/计数器的重复函数(moment.js,node.js)
- 身份validationExpressJS – > passportJs:错误:发送后无法设置标头
- 如何将所有HTTP请求logging到我的Sails.js服务器?