与node和PostgreSQL同步查询

时间:2016-09-16 18:20:12

标签: node.js postgresql

我希望在所有更新查询完成后从box_property删除

我写这段代码,但我不确定这是否正确。我想运行更新查询同步

var data = [1, 2, 3, 4]; //data generate dynamicly  
for (var i = 0; i < BoxData.length; i++) {
    pool.connect(function(err, client, done) {
        client.query("update   box set gamer_id=null where  box_id=$1; ", [data[i]], function(err, resultUpdate) {
            if ((i + 1) == BoxData.length) {
                //when all query finished then run this query
                client.query("delete from box_property where gamer_id=$1;", [gamer_id], function(err, resultUpdate) {})
            }
        })
    })
}

有没有办法运行更新查询同步和for循环之后我运行删除查询?

像这样

var data = [1, 2, 3, 4]; //data generate dynamicly  
for (var i = 0; i < BoxData.length; i++) {
    pool.connect(function(err, client, done) {
        client.query("update   box set gamer_id=null where  box_id=$1; ", [data[i]], function(err, resultUpdate) {
        })
    })
}

//when all query finished then run this query
client.query("delete from box_property where gamer_id=$1;", [gamer_id], function(err, resultUpdate) {})

2 个答案:

答案 0 :(得分:1)

你应该避免在NodeJS中做任何同步。

在您的情况下,一个简单的IN语句应该解决:

var params = [];
for (var i = 1; i <= data.length; i++) {
   params.push("$"+i);
}
 pool.connect(function(err, client, done) {
    client.query("update box " + 
                 " set gamer_id=null " + 
                 " where  box_id in "+params.join(",")+"; ", 
                 [...data], function(err, resultUpdate) {
        client.query("delete from box_property " + 
                     " where gamer_id=$1;", 
                     [gamer_id], function(err, resultUpdate) {})
        })
    })

答案 1 :(得分:1)

使用pg-promise

以正确的方式实施相同的逻辑
var data = [1, 2, 3, 4]; //data generated dynamically

db.tx(t => {
    return t.none('UPDATE box SET gamer_id = null WHERE box_id IN ($1:csv)', [data])
        .then(() => {
            return t.none('DELETE FROM box_property WHERE gamer_id = $1', [gamer_id]);
        });
})
    .then(() => {
        // success
    })
    .catch(error => {
        // error
    });

首先,您不需要为该类型的更新执行循环,单个WHERE IN也可以。另一方面,这种变化的顺序应该在交易中。上面的例子向您展示了如何同时执行这两个操作。