I am new to JavaScript (and Call Backs). In my NodeJS App, I have created an Async function to go and retrieve some userdata from my SQL Database. That works fine, the function DOES retrieve the Data. Then, I am using BCrypt to check if the user supplied password matches the user's 'appPassword'.
This work too!
However, when the password match is successful (OR unsuccessful) I try and return a JSON Object back to the calling function, but the 'result' in the calling function is ALWAYS 'undefined' I don't understand what I am doing wrong here.
Could a JavaScript expert please help?
I have posted my code (Async function and Calling function) below:
NB: The 'result' in the Calling function is ALWAYS 'undefined'
ASYNC FUNCTION
async function VerifyUserByUsernamePassword(userEmail, password) {
const sql = require('mssql')
const { configMSSQL } = require("./db.config.js");
if (sql) sql.close();
return await sql.connect(configMSSQL).then(async pool => {
// Stored procedure
let output_parameter
return await pool.request()
.input('Email', sql.NVarChar, userEmail)
// .output('output_parameter', sql.Int)
.execute('API_READ_USER_BY_EMAIL')
}).then(async result => {
sql.close();
// sql = null;
if (result.recordset.length > 0) {
const appPassword = result.recordset[0].appPassword;
bcrypt.compare(password, appPassword, async function (err, result2) {
if (err) {
console.log(err);
return ({
"message": "failed"
})
}
if (!result2) {
// console.log("result2", result2)
return ({
"message": "failed"
})
}
console.log("result2 was True")
return ({
"message": "success",
"data": result
})
})
} else {
console.log("Error retrieving User Records for Login Verification......");
return ({
"message": "failed"
})
}
}).catch(err => {
sql.close();
// ... error checks
console.log("Error retrieving User Records for Login Verification", err);
return ({
"message": "failed"
});
});
}
CALLING FUNCTION
exports.VerifyLogin = async (req, res) => {
var errors = []
if (!req.body.email) {
errors.push("Credentials Missing");
}
if (!req.body.password) {
errors.push("Credentials Missing");
}
if (errors.length) {
res.status(400).json({ "error": errors.join(",") });
return;
}
var email = req.body.email
var password = req.body.password
const { VerifyUserByUsernamePassword } = require("../database/mssqldb.js");
await VerifyUserByUsernamePassword(email, password).then(async result => {
if (result && result.message === "success") {
res.json(result.data);
} else {
res.json({
"message": "failed",
"User Record ": email
},);
}
}).catch(err => {
console.log(err);
res.json({
"message": "error",
"User Record ": email
},)
})
}