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