Not to mention that you're exposing your code to potential SQL injections, you are handling it improperly. Mysql module is not synchronous and will always execute after console.log (in your example).
There are two things that you can do:
- Use a module that supports async operations (Knex, for example)
- Wrap your code in a promise and execute it asynchronously.
The second example is quite easy to implement. I'll also fix the sql injection part and limit the output to 1;
function getName(id) {
return new Promise(function(resolve, reject) {
connection.query("SELECT name FROM users WHERE id = ? LIMIT 1", [id], function (err, rows, fields) {
if (err) return reject(err);
resolve(rows[0].name);
});
});
}
To run this code, you can use an async/await approach or a promise-based one.
// Async/await:
(async function(){
let name = await getName(1);
console.log(name);
})();
// Promise based:
getName(1).then(function(name) {
console.log(name);
})
Edit:
Knex would make it really easy:
function getName(id) {
return knex.select('name').from('users').where(id,1).limit(1).first();
}
Run it either with async/await or as a promise.