【发布时间】:2017-09-30 18:01:31
【问题描述】:
我一直在尝试使用 MongoDB、Redis、NodeJS 和 socket.io 创建一个包含多个房间的聊天应用程序。我需要查询一个名为 roomDocumentState 的 Redis 列表并将值返回到一个变量中。这个变量必须在全局范围内,需要修改。
我尝试使用的代码只修改了函数中的局部变量。我读过它的东西叫做“关闭”。有人可以告诉我如何正确实施吗?
这里是从Redis中拉取数据并修改变量count_1的代码:
function checkRoomDocumentState() {
var count_1 = 0;
store.llen(roomDocumentState, (err, res) => {
if (err) {
throw err;
}
else {
if (res > count_1) {
count_1 = res;
return count_1;
}
}
});
}
所以这个函数的调用方式如下,这里有一段代码sn-p:
io.sockets.on('connection', client => {
createWhiteboardRooms();
sub.subscribe(roomDocumentState);
store.lpush(roomDocumentState, event1);
//added this to check if there's any value at all
checkRoomDocumentState();
console.log(checkRoomDocumentState());
sub.on("message", (channel, message) => {
console.log(message);
client.send(message);
});
});
【问题讨论】:
-
你想如何使用
count_1? -
基本上,我有这个函数来检查redis列表中的值是否发生了变化。该值将使用 'llen' 获取,然后放入 count_1。第二个函数检查这个变量并做一些其他的事情
-
我问的不是这个变量是如何初始化,而是如何使用。你在哪里打电话
checkRoomDocumentState?如果你想在调用后立即使用这个变量,它将未定义,因为checkRoomDocumentState是异步函数。 -
编辑帖子以显示此内容
-
嘿,my first SO question 差不多!
标签: javascript node.js redis