Wednesday, 28 February 2018

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

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...