异步回调函数,我使用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,它需要该用户标识的索引才能工作:
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...
}
而且我得到的结果是:
userIndex:未定义
我了解到,在indexOfUserInVotingListreturn
行动之前mysql-query
运行立即执行并更新值。
有没有反正我可以强制indexOfUserInVotingList等待查询完成并返回结果?
最重要的一点是,我不想把它转换成异步功能(尽管这种方法是有效的):
indexOfUserInVotingList: function (voteType, articleID, userID, callback) {
//.........
//after query from database
return callback(null,userIndex);
}
..because我不想陷入内部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...
}
}
不可能。如果它是异步的,它保持异步。您不必使用回调,但可以使用承诺。 – Bergi