为什么这个updateSockets()函数接受这样的参数?

时间:2015-07-29 10:27:26

标签: javascript node.js

我正在查看一些在MySQL数据库上执行推送通知的node.js代码。 http://www.gianlucaguarini.com/blog/push-notification-server-streaming-on-a-mysql-database/

有一个轮询功能。

var pollingLoop = function() {

  // Doing the database query
  var query = connection.query('SELECT * FROM users'),
      users = []; // this array will contain the result of our db query

  // setting the query listeners
  query
      .on('error', function(err) {
        // Handle error, and 'end' event will be emitted after this as well
        console.log(err);
        updateSockets(err);
      })
      .on('result', function(user) {
        // it fills our array looping on each user row inside the db
        users.push(user);
      })
      .on('end', function() {
        // loop on itself only if there are sockets still connected
        if (connectionsArray.length) {

          pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);

          updateSockets({
            users: users
          });
        } else {

          console.log('The server timer was stopped because there are no more socket connections on the app')

        }
      });
};

令我困惑的特定代码段就是这个;

      updateSockets({
        users: users
      });

为什么参数users: users

updateSockets()的代码在这里;

var updateSockets = function(data) {
  // adding the time of the last update
  data.time = new Date();
  console.log('Pushing new data to the clients connected ( connections amount = %s ) - %s', connectionsArray.length , data.time);
  // sending new data to all the sockets connected
  connectionsArray.forEach(function(tmpSocket) {
    tmpSocket.volatile.emit('notification', data);
  });
};

2 个答案:

答案 0 :(得分:1)

{
    users : users
}

这段代码只是一个简单的对象。第一个users是对象属性的名称,第二个users只是一个变量。

如果您愿意,可以这样写:

var myUsers = users;
updateSockets({
    users: myUsers
});

答案 1 :(得分:1)

这是存储在数据中的附加信息

当此代码执行emit(data)时,它会发送包含参数usertime的数据包(在updateSockets中添加)

这是您要发送的消息