Sunday, 14 February 2016

javascript - Index loop does not change




I'm trying to gather tweets from twitter, on console if I choose 5 tweets to gather it displays every one of them but if I choose the mysql module to insert them into a database it inserts the last line 5 times.



Can't figure out how to resolve it.



Asking again, had no luck in the last 3 hours making this script work. Was pointed out to for loop does not change index inside function . Can someone please help me fix this problem?



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

Answer



It's because of closures in javascript.




This answer should help explain it and there are a couple ways to handle it.



The easiest being to use .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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...