节点和PostgreSQL同步查询 [英] synchronous query with node and PostgreSQL

查看:309
本文介绍了节点和PostgreSQL同步查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在所有更新查询完成后从 box_property 中删除​​

I want delete from box_property when all update query finished

我写这段代码但我没有确保这是正确的还是不正确的。我要同步运行更新查询

I write this code but I'm not sure that this is correct or not.I want run update query synchronous

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循环之后我运行删除查询吗?

Is there way that run update query sync and after for loop I run delete query?

像这样

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


推荐答案

相同的逻辑,用 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
    });

对于一件事,您不需要为这种类型的更新执行循环,单个在何处。另外,这种变化顺序应该在事务内部。上面的示例向您展示了如何同时执行这两项操作。

For one thing, you do not need to do a loop for that type of update, a single WHERE IN will do. And for another, such sequence of changes should be inside a transaction. The example above shows you how to do both at the same time.

这篇关于节点和PostgreSQL同步查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆