内部有两个异步循环,节点js中有mysql查询

时间:2016-01-27 23:04:50

标签: javascript node.js

我希望按照以下顺序打印我的信息:

enter image description here

这是我到目前为止所做的:

if(!isset($_SESSION['sessionname']['value1']['value2']['value3'])) {
    header("Location:index.php?page=admin");
}

$sql = "INSERT INTO table(value1, value2, value3) VALUES ('".mysqli_real_escape_string($dbconnect,$_SESSION['sessionname']['value1']['value2']['value3'])."')";
$qry = mysqli_query($dbconnect,$sql);
unset($_SESSION['sessionname']['value1']['value2']['value3']);`

但由于一些奇怪的原因,它看起来像这样:

enter image description here

1 个答案:

答案 0 :(得分:0)

这似乎是因为你的connection.query看起来是异步的,你需要将库存从每个循环中分解出来并像这样一次处理一个:

            connection.query('SELECT `keys`.*,`transaction`.*,`keys`.`id` as kid, `transaction`.`id` as tid  FROM `transaction` JOIN `keys` ON `keys`.`id` = `transaction`.`keys_id` WHERE `transaction`.`status_pay`= 1 and `transaction`.`status` = 1').then(function (rows) {
                async.each(rows, function (record, next) {
                    var count = 0;
                    ProcessRow(count, inventory, next);
                });
            });

            function ProcessRow(count, inventory, next)
            {
                if (inventory.length > 0) {
                    console.log(inventory[count].id); /// 4317648454 ... etc..
                    connection.query('UPDATE `transaction` SET `amount_two`= `amount_two` + 1 WHERE `id`= \'' + record.tid + '\'').then(function (err, res) {
                        console.log('3');
                        count++;
                        if(count < inventory.length)
                             ProcessRow(count, inventory, next);
                        else
                             next(); //assumeing you want to call next when you finish processing the inventory for this row.
                    });
                }
            }

你可能需要对&#39;行进行同样的操作。还有? 希望这会有所帮助。

编辑:我没有看到你在你的样本中调用下一个,所以我不确定你什么时候需要它来解雇,但我确实编辑了帖子以反映好像你需要在处理完行后调用它。 / p>