I have a problem with nodejs, in practice as you can see from the two modules that I entered via google drive link, I have a problem with the login form because although I have entered asyn / await in both the functions calls it does not wait but it goes on anyway and in fact it prints the return variable as "undefined". Thanks in advance to everyone who answers!
Router.js :
router.post('/ajax/login', function(req, res, next) {
(async () => {
var loginDb = await login.login(req.body.matricola, req.body.password);
console.log(loginDb);
res.json({output: loginDb, matricola: req.body.matricola});
})();
})
login.js
var response;
async function login(matricola, password){
var conn = connect();
await conn.connect(function(err){
if(!err){
//query ricerca utente nel db
password = md5(password); //cifro la password
conn.query("SELECT * FROM user WHERE matricola=? AND password=?",[matricola, password]
,function(err, result){
if(!err){
if(result.length == 1 && matricola == result[0].matricola && password == result[0].password){
//Invio segnale di logged-in al client
response = "logged-in";
}
else{
response = 'error-login';
}
}
})
}
else{
response = 'error-db';
}
})
return response;
}
exports.login = login;
awaitonly does something useful if youawaita promise. If you're using the originalmysqllibrary, it does not do promises so yourawaitdoes nothing. You would need themysql2library for built-in promise support or you'd have to use one of the exteranal libraries that offers a promise wrapper for mysql. I'd also suggest you read about howasyncandawaitactually work so you better understand how they work and where they work. So many people thinkawaithas some magic powers to just wait for some asynchronous operation. It does not.awaitin combination with traditional callbacks because traditional callbacks are a sign that there is no promise interface in action there. So,await conn.connect(someCallback)will never be how you code withawait. It will just beawait conn.connect().