Node.js chatbox - 从db加载几个最后的消息

时间:2017-01-06 03:04:32

标签: javascript mysql node.js

我正在使用node.js,而我正在尝试基于steam id64进行聊天。如果用户连接到聊天,服务器将从MySQL数据库发送最后2条消息。我在网站上看到的Onyly是两条相同的消息。

function getSteamName(steamid, callback) {
    if (typeof steamid !== 'undefined') {
        var url = "steam api link, because under 10 reputation points" + steamKey + "&steamids=" + steamid;
        request({
            url: url,
            json: true
        }, 
        function (error, response, body) {
            if (!error && response.statusCode === 200) {
                callback(body.response.players[0].personaname);
            }
        })
    }
}

getSteamAvatar与蒸汽API

的其他链接非常相​​似
var sql = "SELECT * FROM `chat` ORDER BY id DESC LIMIT "+count;
connection.query(sql, function(err, rows, fields) {
    rows.reverse();
    for (row in rows) {
        console.log(row);
        var msg = rows[row];
        getSteamAvatar(msg.id64, function(userAvatar) {
            getSteamName(msg.id64, function(userNick) {
                msg["id64"] = userNick;
                msg["avatar"] = userAvatar;
                console.log(msg);
                socket.emit('chat message', msg);
            });
        });
    }
    if (err) throw err;
});

在控制台中我看到:

0
1
RowDataPacket {
  id: 926,
  id64: 'Ezi',
  date: 2017-01-06T02:42:40.000Z,
  message: '454656',
  isDeleted: 0,
  rank: 'Admin',
  avatar: 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c4/c410314bfdfe4fd23bac077212ee79adb99f6848_medium.jpg' }
RowDataPacket {
  id: 926,
  id64: 'Ezi',
  date: 2017-01-06T02:42:40.000Z,
  message: '454656',
  isDeleted: 0,
  rank: 'Admin',
  avatar: 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c4/c410314bfdfe4fd23bac077212ee79adb99f6848_medium.jpg' }

1 个答案:

答案 0 :(得分:2)

  

如果您想查看最新的两条消息,请保留已发送,状态字段,以便您轻松获取最新消息。

     

在您的代码中,您有两次console.log,因此它会在消息中提供两次。请交叉检查..