I just started learning JavaScript and Node.JS and I'm really struggling with the concepts of callbacks. So I went on and tried to implement them to get mySQL data pushed to a site.
I began with this:
// connection stuff happened already. Connection works fine.
app.get('/home', function(req,res){
var sql = `select u.* from users u`;
var sql2 = `select u.* from users2 u`;
usersA = [];
usersB = [];
connection.query(sql, function(error, results, fields){
if (error) throw error;
results.forEach(function(user){
usersA.push({
"id":user.id,
"name":user.name,
"lastname":user.lastname
});
});
connection.query(sql2, function(error, results, fields){
if (error) throw error;
results.forEach(function(user){
usersB.push({
"id":user.id,
"name":user.name,
"lastname":user.lastname
});
});
res.render("index", {
usersA: usersA,
usersB: usersB
});
});
});
});
This works. But I feel like this is the wrong approach considering there could be way more than 2 queries.
I need to get both arrays filled before the index is rendered. And I'd like to achieve that a little more straightforward without nesting multiple queries within each other.
Maybe I'm just not used to code looking like that. If this is a valid approach even for 10 or more querys I'll just stick with it. It just feels wrong.
So I started looking into this SO thread and tried to somehow get things to work but it didn't:
function executeQuery(query, callback) {
connection.query(query, function (err, rows, fields) {
if (err) {
return callback(err, null);
} else {
return callback(null, rows);
}
})
}
function getResult(query,callback) {
executeQuery(query, function (err, rows) {
if (!err) {
callback(null,rows);
} else {
callback(true,err);
}
});
}
function getUsers(sqlQry){
getResult(sqlQry,function(err,rows){
if(!err){
return rows;
} else {
console.log(err);
}
});
}
With this prepared I tried the following:
var sql = `select u.* from users u`;
var sql2 = `select u.* from users2 u`;
app.get('/home', function(req,res){
res.render("index", {
usersA: getUsers(sql),
usersB: getUsers(sql2)
});
}
But my usersA/usersB are empty. I guess that's some kind of scoping/asynch problem as getUsers() returns before the query is executed.
From what I've read so far this might be a good place for promises.
I added an answer with my solution.