【问题标题】:Mysql-nodejs nested queriesMysql-nodejs 嵌套查询
【发布时间】:2015-02-07 17:47:40
【问题描述】:

它说无法读取 socket.broadcast 行中的属性authorid undefined。

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

【问题讨论】:

  • console.log 输出什么?

标签: javascript mysql node.js express


【解决方案1】:

问题是i的值在使用socket的时候是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);

【讨论】:

  • 谢谢。有效。但我似乎无法理解为什么我被套接字使用?
  • i 在您调用 socket.broadcast.to(rows[i].authorid) 时被 socket 使用。 i的值大于行的长度,所以rows[i]中没有元素
  • 哦是不是因为查询是异步的?
  • 例如有一个包含 3 个元素的列表。行[作者_1,作者_2,作者_3]。您在for 循环中使用此列表。您可能会认为,当您第一次调用 socket.broadcast.to.. 时,i 的值是 0,而您正在使用 rows[0] =&gt; meaning author_1。好吧,这是错误的。您实际上正在访问不存在的rows[3]。而且你已经知道原因 => 异步调用
  • 太棒了。谢啦。你太棒了。
猜你喜欢
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
  • 2019-05-25
  • 2014-08-26
  • 1970-01-01
相关资源
最近更新 更多