【发布时间】:2017-04-07 12:57:00
【问题描述】:
我正在使用 Express JS 和 mysql2-node 模块来创建访问 MySQL 数据库的函数
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;
}
我在这个函数中调用了这个函数 - upvoteInArticleFromUser,它需要该用户 ID 的索引才能工作:
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...
}
我得到了结果:
用户索引:未定义
我了解到 indexOfUserInVotingList 中的return 操作在mysql-query 运行并更新值之前立即执行。
我是否可以强制 indexOfUserInVotingList 等待查询完成并返回结果?
最重要的一点是,我不想把它变成异步函数(尽管这种方法可行):
indexOfUserInVotingList: function (voteType, articleID, userID, callback) {
//.........
//after query from database
return callback(null,userIndex);
}
..因为我不想被困在 callbackhell 中,比如:
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...
}
}
【问题讨论】:
-
不可能。如果它是异步的,它会保持异步。不过,您不必使用回调,您可以使用 Promise。
标签: javascript node.js asynchronous callback