我的代码:
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);
}
});
}
}
});
}
当我给出行[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/