一时半会的还没有习惯 js 的执行方式,设置状态量返回 undefined 后,我意识到,在 java 里使用的方法在 nodejs 是执行不通的~
所以需要使用回调函数。
那么该怎么使用呢?
首先要在函数里面传入回调函数这一参数。
我以我验证用户的代码作为示例。
我是将验证用户是否存在这一类函数写在单独的文件里,然后作为接口。
代码如下:
exports.findUserByAccount = function(account,password,callback){
var sql = "select * from users where account = ?";
var params = [account];
db.Excute(sql,params,function(err,vals,fields){
if(vals.length == 0){
callback(false);
console.log("error!the user dose not exist!");
return;
}
else {
console.log("excute!");
if(vals[0].password == password){
callback(true);
console.log("find user success!");
}
else{
callback(false);
console.log("not err but the psw is incorrect!");
}
}
})
}
可以看到我有一个 callback 的参数。然后将 sql 语句的执行状态作为结果在 callback 函数中返