答案 0 :(得分:1)
首先,由于i
中的rows[i]
超出索引范围,因此未定义。但是,当你在for循环中执行多个异步任务时,解决这个问题不会解决你的问题。打印时不会填充您的行对象。
解决方案:您需要使用异步或承诺来执行任务。
// Include the async package
var async = require("async");
client.connection.query('select * from shop',function(err,rows){
if(rows.length>0)
{
// 1st para in async.each() is the array of items
async.each(rows,
// 2nd param is the function that each item is passed to
function(item, callback){
// Call an asynchronous function,
var shopIdFetched = item.shopId;
client.connection.query('select * from image where shopId=?',shopIdFetched,function(err,data){
if(data.length > 0){
item.image = JSON.stringify(data);
}
callback();//required
});
},
// 3rd param is the function to call when everything's done
function(err){
if(err){
console.log('Error:' + err);
}
console.log(rows);// your result
}
);
}
});
答案 1 :(得分:0)
退出循环时,i
的值等于数组的长度。
假设长度为10,因此索引从0到9。
所以事实上,在循环之后,rows[i]
是rows[10]
,这确实是未定义的。