【问题标题】:Resetting variables and async programming in NodeJS在 NodeJS 中重置变量和异步编程
【发布时间】:2016-05-26 08:07:58
【问题描述】:

我在 nodeJS 中玩异步编程,遇到了一个有趣的问题。

我的代码中有这样的内容:

// require modules
var clientDetails = {}; // Initialize the object at the top of the file.

io.use(authenticate) // a method which gets some user information from the database and assigns the socket ID to the user. clientDetails object gets the data here.

io.on('connection', socketIOConnection); // A method which calls some methods using promises to control the flow of the method calls and socket.on('disconnect') event.
redisClient.on('message', redisMessage); // An event for redis pub/sub 

function socketIOConnection(socket) {
    // a few method chain calls to control the async flow
    storeUserDetailsToRedis().then().then().then().then() 
    socket.on('disconnect', socketIODisconnect)

}

function socketIODisconnect() {
  // a few chain calls to control the async flow. 
  removeUserDetailsToRedis().then().then().then().then()
}

我正在寻找一种在套接字 IO 连接(或断开连接)事件结束后清除客户端详细信息对象的方法。或者换句话说,所有的承诺都被解决了。

目前,如果我尝试正常执行 clientDetails = {},它将首先执行并且应用程序将失败/具有未定义的数据。

我需要清除 clientDetails 对象,以便在每次页面刷新时都有一个新对象。不清除,它仍然保留旧数据并弄乱我存储在那里的redis用户信息数据。

我在这个项目中使用套接字 IO 和 Redis。

有人知道如何在保持异步控制的同时清空 clientDetails 对象吗?

【问题讨论】:

    标签: node.js asynchronous redis socket.io


    【解决方案1】:

    我找到了解决这个问题的方法。我在套接字本身上添加了 clientDetails 对象,而不是将其作为文件顶部的变量。现在我可以访问所有事件,但我必须将它作为参数添加到我的所有方法中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-04
      • 2015-10-08
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      相关资源
      最近更新 更多