2015-10-19 51 views
1

我试图从twitter上,在控制台上收集鸣叫,如果我选择5个鸣叫来收集它显示每一个,但如果我选择将它们插入到数据库的MySQL模块,它插入最后线5次。索引循环不会改变

无法弄清楚如何解决它。

再次问,在过去的3个小时内没有运气使这个脚本工作。被指出for loop does not change index inside function。有人可以帮我解决这个问题吗?

for (var i = 0; i < data.length ; i++) { // get all the messages from username, devfined in search term 
    var retweetId_str = data[i].id_str; // id_str = id not rounded more precise 
    console.log('id_str:', retweetId_str); // 

//id_str: 656087507604402176 
//id_str: 656063345192255488 
//id_str: 656063056947126272 
//id_str: 656062911530606592 
//id_str: 656062750574182400  
    con.query('SELECT retweetid_str FROM droid_retweets WHERE retweetId_str=?', retweetId_str, function(error,result){ 
    console.log('id_str:', retweetId_str);   

    //id_str: 656062750574182400 
    //id_str: 656062750574182400 
    //id_str: 656062750574182400 
    //id_str: 656062750574182400 
    //id_str: 656062750574182400 
    }); 
} // for close 
+2

检查文档,查询可能是一个异步方法,以便通过查询运行时间,retweetId_str总是656062750574182400 – juvian

回答

1

这是因为在JavaScript中关闭。

This答案应该有助于解释它,并且有几种方法可以处理它。

最简单的幸福使用.forEach()

data.forEach(function(d) { // get all the messages from username, devfined in search term 

      var retweetId_str = d.id_str; // id_str = id not rounded more precise 
      console.log('id_str:', retweetId_str); // 
      con.query('SELECT retweetid_str FROM droid_retweets WHERE retweetId_str=?', retweetId_str, function(error,result){ 
      console.log('id_str:', retweetId_str);   

      }); 

    }); // for close 
+0

这不是因为关闭。这是因为变量的范围如何。 – 2015-10-19 18:23:27

+0

最后一个有效的例子。非常感谢你。你不知道我有多感激。 –

+0

我将在4分钟内添加此答案,再次感谢 –

1

这是因为你从con.query响应之前的循环已经执行的所有迭代,这就是为什么它打印的最后一个好几次,因为该指数处于最后的位置

+0

我也明白,但我不知道该怎么在我的例子中实现 –