2015-02-07 132 views
1

它说无法读取属性authorid未定义在socket.broadcast行。Mysql-nodejs嵌套查询

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); 
+0

什么的的console.log输出? – satchcoder 2015-02-07 17:52:14

回答

1

的问题是,的i值使用套接字时是rows.length

您可以通过创建一个函数,它发送当前行或发送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); 
+0

谢谢。有效。但我似乎无法理解为什么我被socket使用? – 2015-02-07 18:10:38

+1

当你调用socket.broadcast.to(rows [i] .authorid)''时,'''被'socket'使用。 “i”的值高于行的长度,所以'rows [i]中没有元素' – 2015-02-07 18:12:15

+1

哦,是因为查询是异步的吗? – 2015-02-07 18:15:05