NodeJS中的执行顺序

时间:2017-07-11 00:48:14

标签: mysql node.js

我正在将PHP代码转换为NodeJS。我正在运行几个MySQL查询,然后我会根据这些结果运行其他的查询。但是,似乎MySQL查询在NodeJS中以特定顺序运行,这导致了一个错误。这是我的代码的样子:

    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;
                }
            })

似乎MySQL查询是在循环之后运行的,因此“i”变量的值为“2”。我是对的吗?

有没有办法将属性添加到“result”数组?

由于

0 个答案:

没有答案