回调函数中如何根据条件循环查找相同sql数据库?或者说回调函数怎样实现无限次递归调用?
请看下面代码逻辑,问题在下面代码的中文里。真心求教!
function GetRandomNum(Min,Max)
{
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
Member.get_user_code = function(callback){
var user_code= GetRandomNum(100,100000000);
Member.get(user_code,function(err,member){
if(err)throw err;
if(member){
user_code= GetRandomNum(100,100000000);
//这里需要实现重新生成user_code并执行检查数据库,直到检查到数据库中不存在该user_code为止,请问这里的逻辑怎么实现?
//或者说如何循环执行Member.get函数直到此函数返回值为null为止呢?
......
}
callback(user_code);
});
}
Member.get = function(user_code,callback){
var member = null;
mysql.connection(function(connection){
connection.query('select * from members where user_code=?',user_code,function(err, results, fields){
if(results && results.length > 0){
member = new Member(results[0]);
}
callback(err,member);
});
});
}
1 回复
自己搞定了,参考了async库的whilst函数写法,改后如下:
function GetRandomNum(Min,Max)
{
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
function check(err, member,uc, callback){//把判断逻辑整理为函数
if(err) throw err;
if(!member){//直到member为空为止,执行Member.get_user_code的callback
callback(uc);
}else{
uc = GetRandomNum(100,100000000);
Member.get(uc,check, callback);//再次回调Member.get
}
}
Member.get_user_code = function(callback){
var uc = 5919211;//GetRandomNum(100,100000000);
Member.get(uc, check, callback);
}
Member.get = function (user_code, callback, callback2){//传送两个函数,第一个用来传check函数,第二个传Member.get_user_code的callback
mysql.connection(function(connection){
connection.query(
'SELECT * FROM members where user_code = ?', user_code,
function selectCb(err, results, fields) {
if (err) {
throw err;
}
connection.end();
var member = null;
if(results && results.length > 0){
member = new Member(results[0]);
}
callback(err,member, user_code,callback2);
}
);
});
};
最后在调用的方法是:
Member.get_user_code(function(uc){
......
});