I'm writing code to connect to SQL Server from express.js. Everything is fine but I want to return error at the end of function. I declared global variable and if error I'm assigning error to that variable and returning at the end. But still that variable value I'm getting undefined. Please someone help me on this.
Here is the code:
async function mysqlConnection(userParam) {
var config = {
user: userParam.connectionUsername,
password: userParam.connectionPassword,
server: userParam.hostname,
database: userParam.databaseAccount,
};
var msg
let connection=sql.connect(config, function (err) {
if (err) {
console.log(err.message);
msg=err.message // return err;
} else {
console.log("Done");
}
return msg
});
console.log(msg)
return msg
}
Tried this too...
async function mysqlConnection(userParam) {
var config = {
user: userParam.connectionUsername,
password: userParam.connectionPassword,
server: userParam.hostname,
database: userParam.databaseAccount,
};
var msg
try {
let connection=await sql.connect(config);
return msg; // undefined
} catch (err) {
console.log(err.message);
msg = err.message;
return msg;
}
}
Here msg
is a global variable and and I'm assigning value inside if condition and I'm returning that variable before function end but I'm getting undefined if connection fails instead of error message, but inside if condition I'm getting error message. Please can someone suggest a solution for this?
Thank you