0

I have the following bit of code in Node.js.

function homeCallback(reply, twid) {
    var c = reply.length;

    for (var i = c - 1; i >= 0; i--) {
        var isRT;
        var tweet_id;

        if (reply[i].hasOwnProperty('retweeted_status')) {
            tweet_id = reply[i].retweeted_status.id_str;
            isRT = true;
        } else {
            tweet_id = reply[i].id_str;
            isRT = false;
        }

        console.log(tweet_id);
        var existsQ = "SELECT * FROM tweets WHERE tweet_id=" + connection.escape(tweet_id);

        connection.query(existsQ, function (err, rows) {
            console.log(tweet_id);
            //need to use tweet_id here
        });
    }
}

reply is a json response from a call to stauses/home_timeline of Twitter's API, connection is a mysql connection

If there are a couple of tweets in reply with ids of 11 and 12 I get an output like this:

11
12
12
12

Although I expect an output like this:

11
12
11
12
17
  • What is c? I don't see it defined anywhere?
    – Xotic750
    Feb 17, 2014 at 17:16
  • oops I had deleted that line. Added it back.
    – Jasjeev
    Feb 17, 2014 at 17:18
  • Are you able to create a jsFiddle using this code to demonstrate?
    – Xotic750
    Feb 17, 2014 at 17:21
  • I can't because of connection
    – Jasjeev
    Feb 17, 2014 at 17:27
  • Perhaps you could use some canned data to demonstrate.
    – Xotic750
    Feb 17, 2014 at 17:28

1 Answer 1

0

The callback on connection.query() would execute asynchronously while local variable tweet_id scoped in the for-loop might get overwritten by next iteration.

Try to duplicate tweet_id inside a closure/function call.

(function(tid) {
        console.log(tid);
        var existsQ = "SELECT * FROM tweets WHERE tweet_id=" + connection.escape(tid);

        connection.query(existsQ, function (err, rows) {
            console.log(tid);
            //need to use tweet_id here
        });
})(tweet_id);

This is not ideal, but would give you some idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.