gpt4 book ai didi

javascript - 在Nodejs中获取 undefined variable

转载 作者:行者123 更新时间:2023-11-30 16:34:32 25 4
gpt4 key购买 nike

我正在使用 Node 来运行这段代码

但是当我运行这段代码时,get 函数中的 leadid 变量得到了未定义的返回:

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);

在其他方面,当我在主文件中调用这个函数(搜索)

new call.hangup.searching(number, connection, validator);

一切正常

我该如何解决?

最佳答案

您需要记住,JavaScript 是异步的。

当调用 searching 时,数据库查询是异步发出的,函数在数据库给你结果之前返回。换句话说,您的 searching 函数不会为您提供

的结果
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 将在数据库查询返回时调用的回调函数。

所以你的解决方案应该是这样的:

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对 promise 做同样的事情。

关于javascript - 在Nodejs中获取 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32882960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com