app.post('/login', function (req, res) {
var login = req.body.login;
var pass = req.body.pass;
var ret = CheckUserValid(login, pass);
res.send(ret);
})
function CheckUserValid(login, pass,callback) {
var sql = "SELECT * FROM `user` WHERE login = ? AND pass= ?";
client.query(sql, [login, pass], function selectResutl(err, results, fields) {
console.log(results);
if (!err) return true;
else
throw err;
});
}
first Function is about request and second is about making call to mysql. because it's async so it's not worked. Can someone let me know how I can make it work synchronously like in C#.
The signature of your CheckUserValid
method already implies a callback
. You can use that to call something when your db-request is done, like this:
app.post('/login', function (req, res) {
var login = req.body.login;
var pass = req.body.pass;
// use a closure here for the callback of checkUserValid
checkUserValid(login, pass, function(err, isValid) {
// send the response when checkUserValid is done
res.send(isValid)
});
})
function checkUserValid(login, pass, callback) {
var sql = "SELECT * FROM `user` WHERE login = ? AND pass= ?";
client.query(sql, [login, pass], function(err, results, fields) {
console.log(results);
if (!err) {
// there is no error, pass null for the error
// and true for the result
callback(null, true);
} else {
// an error occurred in the db-query
// pass it to the callback
callback(err)
}
});
}
By convention you should pass the err
as first argument, but in the end that's up to you. However you can pass the original error up to your initial function and handle it there.
你应该看一下Fibers模块。
You can chain the functions that you want to call in order
eg you can make res.send(ret);
as the callback of your CheckUserValid
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.