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
Jasjeev
  • 385
  • 1
  • 4
  • 17

1 Answers1

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.

palanik
  • 3,601
  • 1
  • 13
  • 10