在循环之外时,值更改为undefined

rows [i]的值完全是在循环内打印的,但是当我们在外面打印时,它变得不确定。我不想在我的程序中使用set timeout函数。

function listshops(callback) { client.connection.query('select * from shop',function(err,rows){ if(rows.length>0) { 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){ var result = rows[i].image = JSON.stringify(data); } }); })(i); } console.log(rows[i]); } }); } 

输出: 产量

首先你得到未定义,因为你的i rows[i]是索引不足。 但是,解决这个问题不会解决你的问题,因为你在for循环中执行多个asynchronous任务。 您的行对象在打印时不会被填充。

解决scheme:您需要使用asynchronous或承诺执行任务。

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

当你退出循环时, i的值等于数组的长度。

假设长度是10,所以索引从0运行到9.所以实际上,在循环之后, rows[i]rows[10] ,这实际上是未定义的。