'Cannot change variable values from a callback scope
I designed a function that connects to MYSQL and calls the callback parameter with the 'connection' object. I'm calling this function(lets call it A) inside another function (lets call it B), and, in the callback I'm sending to function A, I'm trying to modify a value from function B, but it doesn't work. Simply the value remains the same.
The code:
Function A:
function databaseConnection(callback) {
// MYSQL Connection Details
const connectionDetails = {
host: 'localhost',
user: 'root',
password: 'Mobileapp!?',
database: 'social-app'
}
//
// Configuring the connection
const connection = mysql.createConnection(connectionDetails);
connection.connect();
//
// Calling the user callback
callback(connection);
//
// Ending database connection
connection.end();
//
}
Function B:
function isLoginDataValid(username, password) {
let valid = true;
// Starts the database connection and execute the given callback with the supplied object 'connection'
databaseConnection(connection => {
connection.query(`SELECT id from users where username = '${username}' and password = '${password}'`, (error, results, fields) => {
if (!error && !(results.length))
valid = false;
})
})
//
return valid;
}
Thank you!.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
