I'm using Express JS
with mysql2-node
module to create a function that access MySQL database
indexOfUserInVotingList :
indexOfUserInVotingList: function (voteType, articleID, userID) {
SQLconnection.connectToServer();
db = SQLconnection.getConnectionInstance();
let userIndex;
switch (voteType) {
case "upvote":
db.query('SELECT upVoters FROM article WHERE article.idArticle = ?', [articleID], function (err, rows) {
if (err) {
throw err;
} else {
let upvoterArray = rows[0].upVoters;
userIndex = upvoterArray.indexOf(userID);
}
});
break;
case "downvote":
db.query('SELECT downVoters FROM article WHERE article.idArticle = ?', [articleID], function (err, rows) {
if (err) {
throw err;
} else {
let downvoterArray = rows[0].downVoters;
userIndex = downvoterArray.indexOf(userID);
}
});
break;
default:
break;
}
return userIndex;
}
and I call this function inside this one - upvoteInArticleFromUser, which need the index of that userID to work:
upvoteInArticleFromUser: function (articleID, userID, callback) {
SQLconnection.connectToServer();
db = SQLconnection.getConnectionInstance();
let userIndex = this.indexOfUserInVotingList('upvote',articleID,userID);
console.log("userIndex: "+userIndex);
// the rest of the code was cut shorted...
}
And I get the result:
userIndex: undefined
I learnt that return
action in indexOfUserInVotingList executed immediately before mysql-query
run and update the value.
Is there anyway I can force the indexOfUserInVotingList to wait for the query to finish and return the result ?
The most important point is, I don't want to turn that into async function (although this approach would work):
indexOfUserInVotingList: function (voteType, articleID, userID, callback) {
//.........
//after query from database
return callback(null,userIndex);
}
..because I don't want to stuck inside callbackhell, like:
upvoteInArticleFromUser: function (articleID, userID, callback) {
//.....
indexOfUserInVotingList('upvote',articleID,userID,function(err,index){
if(err) throw err;
else
{
this.userIndex = index;
// the whole remaining code for processing would be nested inside this one...
}
}