我有以下代码,并正在尝试使用 node.js 制作转盘机器人。这段代码说,当用户键入“q+”时,我们必须确保它还没有在队列中,它还不是 DJ,如果它满足这两个要求,则将它们添加到队列中。否则,如果它不满足前两个条件之一,请告诉用户并且不要触摸队列。
我的问题是“isCurrentDJ(userId)”。当我通过该函数传递 userId 时,该函数给了我正确的答案。然而,即使答案是“真”并且 isCurrentDJ(userId) 函数中的 console.log() 函数证明了这一点,该函数也总是会传回“假”。
我不是最精通 js 的人,所以我认为这可能是一个变量范围问题。但我真的不确定,并且已经为此苦苦挣扎了好几个小时!任何帮助将不胜感激。谢谢!
// When someone speaks, listen to see if it is one of the q commands
bot.on('speak', function (data) {
var name = data.name;
var text = data.text;
var userId = data.userid;
// q+ :: Add to Queue
if (text.match(/^q\+$/)) {
//Index is the position in the queue that this person's name is found.
//If its not found, -1 is returned.
var index = queue.indexOf(name);
//Function to determine if the user is currently a DJ
function isCurrentDJ(user_id, callback){
bot.roomInfo(false, function (data) {
var djList = data.room.metadata.djs;
for (i = 0; i < djList.length; i++){
if (djList[i] == user_id){
console.log('recognized as a DJ'); //Consistently printed!
callback(true);
}
}
callback(false);
});
}
isCurrentDJ(userId, function(isDJ) {
//If the user is already in the queue
if(index > -1){
//Tell them they are already in there
bot.speak('You are already on the list');
} else if(isDJ){
//Otherwise if they are already a DJ tell them that
bot.speak('You are already a DJ, '+name);
}else{
//Otherise if they are not in the queue add user to end of queue
queue.push(name);
//Tell them about it and the updated q
bot.speak(name+' has been added to queue.');
}
});
}