如何从 pg-promises 中的子承诺向父承诺抛出错误

How to thow error to parent promise from child promise in pg-promises

我有两个 table "A" 和 "B"。我想在 table "B" 中创建一行,其中包含 table "A" 的主键并且整个操作应该是原子的。

function test(data, res) {
    let query1 = knex.insert([data], "id").into("A").toString();
    let query2 = "";
    db.tx(function (t) {
        return this.batch([
            t.one(query1).then(function (id) {
                query2 = knex.insert({A_id:id, x:x, y:y}).into("B").toString();
                t.none(query2).catch(function (error) {
                    console.log(error);  // want to pass this error to next catch block
                });
            })
        ]);
    }).then(function () {
        console.log("success");
    }).catch(function (error) {
        console.log(error);
    });
}

每当嵌套承诺出现错误时,我想拒绝父承诺并将该错误传递给父承诺。

成功了....必须 return 来自 child parent 的承诺,即 t.none() 没有 catch()

我是 pg-promise 的作者。它具有编写非常干净的代码的所有正确要素:

function test(data) {
    db.tx(async t => {
        let b = await t.one('INSERT INTO B(col1, col2) VALUES(${prop1}, ${prop2}) RETURNING id', data);
        await t.none('INSERT INTO A(col1, col2) VALUES(, )', ['bla', b.id]);
    })
        .then(() => {
            console.log('SUCCESS');
        })
        .catch(error => {
            console.log('ERROR:', error);
        });
}

你的例子中根本不需要使用t.batch,使用ES7异步是最好的。

如果你真的想自动生成插入,请参阅 helpers 命名空间,不需要第三方库。