Mysql-nodejs嵌套查询
它说,不能读取socket.broadcast行中未定义的属性authorid
。
setInterval(function(){ db.query("select * from `notifications`", function(err, rows){ if (rows.length>temp){ for (var i=temp; i<rows.length; i++){ console.log('sending room post', rows[i].authorid); db.query("select `name` from `users` where `id`=?", [rows[i].authorid ], function(err, name){ name=name[0].name; socket.broadcast.to(rows[i].authorid).emit('new notification', { authorname:name, dpid:rows[i].followid, read:rows[i].read, type:rows[i].type, followstatus:1 }); }); } temp=rows.length; } }) }, 3000);
问题是,使用套接字时, i
的值是rows.length
。
你可以通过创build一个你发送当前行或者发送index
并使用rows[index]
的函数来解决这个问题:
setInterval(function() { db.query("select * from `notifications`", function(err, rows) { // You access the values of the current row // row.authorid // ... var broadcast = function(row) { console.log('sending room post', row.authorid); db.query("select `name` from `users` where `id`=?", [row.authorid], function(err, name) { name=name[0].name; socket.broadcast.to(row.authorid).emit('new notification', { authorname: name, dpid: row.followid, read: row.read, type: row.type, followstatus: 1 }); }); }; if (rows.length>temp) { for (var i=temp; i<rows.length; i++) { broadcast(rows[i]); } temp=rows.length; } }) }, 3000);