您的位置:首页 > 数据库 > MySQL

express 获取mysql执行结果的状态问题

2018-04-12 16:12 363 查看
一时半会的还没有习惯 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 函数中返回。
调用代码如下:userDao.findUserByAccount("cc","cc",function(states){
console.log(states);
});这样就能获取 sql 语句的执行状态了。然后可以将这个状态返回给前端:
代码如下:exports.userLogin = function(req,res,next){
var password = req.body.password;
var account = req.body.account;
userDao.findUserByAccount(account,password,function(states){
if(states){
res.send('{"result":"true"}');
}else{
res.send('{"result":"false"}');
}
});

}这样就能够将状态返回给前端了。回调函数还是挺神奇的,但是我一时半会还用不习惯。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: