1

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
1
  • 2
    check docs, query is probably an async method so by the time the queries run, retweetId_str is always 656062750574182400 Commented Oct 19, 2015 at 18:18

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

8 Comments

It's not because of closures. It's because how variables are scoped.
Finally an example that works. Thank you very much. You don't know how grateful I am.
I'll add this as an answer in 4min, Thanks again
@Alex_TNT: The answer you were linked to in your previous question and here give this exact solution.
It might mean the exact solution for you that might be fluent in javascript but for me as a beginner and only experience I have is with html and 2d/3d graphic designing it's not the same solution.
|
1

It's because the for loop has executed all the iterations before you get response from con.query, that's why it prints the last one several times, because the index is at the last position

1 Comment

I did understand that but I don't know how to implement in my example

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.