在循环外部时,值变为undefined

时间:2016-06-09 05:33:47

标签: node.js express

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

pip,virtualenv and youtube-dl

输出:output

2 个答案:

答案 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],这确实是未定义的。