node.js - 在nodejs中执行sql查询时返回未定义的值

标签 node.js express

我正在从包含表的数据库中获取值: tables

我的代码:

function listshops(callback)
{   
 client.connection.query('select * from shop',function(err,rows){
   if(rows.length>0)
   {  
     for(var i=0;i<rows.length;i++)
     {   
       var shopIdFetched = rows[i].shopId;
        client.connection.query('select * from image where shopId=?',shopIdFetched,function(err,data){
           if(data.length > 0){
            console.log(rows[i],data);
            }

        });

     }

   }

 });
}

但是在显示结果时,第一个查询显示未定义的值。 enter image description here

当我给出行[0]和行1时正在获取值。但我需要实现 rows[i]。

最佳答案

您误解了异步调用是如何进行的。

运行这部分代码时会发生什么?

     for(var i=0;i<rows.length;i++)
     {   
       var shopIdFetched = rows[i].shopId;
       client.connection.query(...) //these are asynchronous methods    
     }

对于rows.length=10,它会调用10次client.connection.query,不幸的是这是异步方法,因此它还没有执行,但它把10个异步方法放入事件堆栈。

该方法同步完成后,其中一个方法指示,数据库调用完成,执行该方法,就是这个

        if(data.length > 0){
             console.log(rows[i],data);
        }

但是此时,for 循环已经完成,i=10,因此 rows[10] 未定义(因为对于 rows.length=10,您的数据位于 rows[0]rows[9]

<小时/>

一种解决方法是将另一种方法放入内部作用域,如下所示

for(var i=0;i<10;i++)
{
    x(i);
}

function x(i){
    console.log(i);
    //this i will be same even after asynchronous paradighm
}
<小时/>

同样的事情可以写成这样

for (var i = 0; i < 10; i++) {
    (function(i){
        console.log(i);
    })(i)
}

就你的情况

 for(var i=0;i<rows.length;i++)
 {   
   (function(i){
   var shopIdFetched = rows[i].shopId;
    client.connection.query('select * from image where shopId=?',shopIdFetched,function(err,data){
       if(data.length > 0){
        console.log(rows[i],data);
        }

    });
    })(i);
 }
<小时/>

为了更好地理解,这会做同样的事情

 for(var index=0;index<rows.length;index++)
 {   
   (function(i){
   var shopIdFetched = rows[i].shopId;
    client.connection.query('select * from image where shopId=?',shopIdFetched,function(err,data){
       if(data.length > 0){
        console.log(rows[i],data);
        }

    });
    })(index);
 }

在前面的示例中,我们只是用不同的变量 i 隐藏了变量 i (如果创建了更多同名变量,则将选择最内部作用域中的变量)

关于node.js - 在nodejs中执行sql查询时返回未定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37702932/

相关文章:

node.js - expressjs设置tls连接https nginx服务器进行请求

node.js - 使用Backbone.js框架如何进行ajax调用快速路由

javascript - Expressjs/Node.js - res.redirect() 未加载页面

javascript - 如何使用 NodeJS 发送带有文件名和文件扩展名的文件流

javascript - 替代 Node 中的 fork 过程?

javascript - Mongoose:更新文档时转换为日期失败

javascript - 断开连接后套接字不会清理

JavaScript/NodeJS : Invoking object methods inside the same object: why is "this." mandatory?

javascript - 流类型和合并json对象

node.js - NodeJS Passport 按路由配置,添加为中间件并且没有错误,但它不起作用/触发