All queries to databases or requests to an endpoint etc in Javascript are processes asynchronously meaning they will not be executed in the usual course of the execution. Rather these callbacks will be invoked when the process is executed in your case, when the query is done on the database and the repsonse is returned
Now, you can use multiple approaches to deal variables in this scenario but since you wanted to access the variable right after your database query, you can try the below.
Using ASYNC / AWAIT
// YOU CAN USE AWAIT ONLY INSIDE AN ASYNC FUNCTION
async function mysqlselect(db, data) {
const uIdPromise = return newPromise((resolve, reject) => {
let sql = `SELECT id, name FROM users WHERE name = '${data.uName}'`;
db.query(sql, function (err, result) {
if (err) reject(err);
resolve(result[0].id);
});
})
// You can access uId right away here.
const uId = await uIdPromise;
};
NOTE: If you want to however return this variable and try to access it somewhere you won't be able to do it because an async
function will always return a Promise. You would have to either await
on an async
function or perform a .then