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

一时半会的还没有习惯 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"}');
    	}
    });
    
}

这样就能够将状态返回给前端了。回调函数还是挺神奇的,但是我一时半会还用不习惯。

猜你喜欢

转载自blog.csdn.net/wsh2467991332/article/details/79915355