0

I'm converting a PHP code to NodeJS. I was running a couple MySQL queries, then I would run other ones based on these results. However, it seems like MySQL queries are run in a particular order in NodeJS, which is causing a bug. Here's what my code looks like:

    console.log("performing search : "+sql);
    con.query(sql, function (err, result) {
        if (err) throw err;
        for (var i = 0; i < result.length; i++) { // "result" has 2 items
            sql = "select content, case when date < CURDATE() then DATE_FORMAT(date,\"%d/%m %k:%i \") else DATE_FORMAT(date, \"%k:%i \") end as time from Messages where recipient="+ result[i].conversation_id +" order by date desc limit 0,1";
            console.log(i + ' ---- ' + result[i]) // outputs "0 [object Object]", then "1 [object Object]"
            con.query(sql, [result, i], function(err, _result){ // I'm passing the results and the index as parameters, and I'm storing the temporary results in "_result"
                if(_result.length != 0){
                    console.log('-----------')
                    console.log(i + ' ' + result[i]) // Outputs "2 undefined", which causes a crash
                    console.log('-----------')

                    result[i].last_message = _result[0].content;
                    result[i].last_message_time = _result[0].time;
                }
            })

It seems like the MySQL query is run after the loop, so the "i" variable has a value of "2". Am I correct?

Is there any way to add attributes to the "result" array?

Thanks

user1319182
  • 481
  • 12
  • 26
  • 1
    There are a hundred duplicates of this type of question as it's a common newbie misunderstanding. Asynchronous operations are non-blocking in Javascript. That means your `for` loop runs to completion and then your queries finish LATER, thus the value of `i` is messed up. Just change your `for (var i = 0 ....)` loop to `result.forEach(function(val, index) { ... })` and each iteration of the loop will have it's very own value for `index`. Or, in ES6 you can use `for (let i = 0; ....)` and each iteration of the loop will also have it's own value of `i`. Either way, the problem will be gone. – jfriend00 Jul 11 '17 at 06:34
  • Well, you also have to modify the code in your `for` loop to use `val` and `index` if you're using the `.forEach()` option. – jfriend00 Jul 11 '17 at 06:36
  • @jfriend00 Thanks. It did the trick. – user1319182 Jul 12 '17 at 01:51

0 Answers0