javascript - 如何从 pg-promises 中的子 promise 向父 promise 抛出错误

标签 javascript promise es6-promise knex.js pg-promise

我有两个表“A”和“B”。我想在表“B”中创建一行,其中包含表“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);
    });
}

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

最佳答案

我是 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($1, $2)', ['bla', b.id]);
    })
        .then(() => {
            console.log('SUCCESS');
        })
        .catch(error => {
            console.log('ERROR:', error);
        });
}

您根本不需要在您的示例中使用 t.batch,它是使用 ES7 async 的最佳选择。

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

关于javascript - 如何从 pg-promises 中的子 promise 向父 promise 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40701968/

相关文章:

javascript - 如何使输入字段中的文本在提交后显示在屏幕上?

javascript - 为什么 "reject"在此代码中实际上并未拒绝?

node.js - 在 Node.js 中同步使用另一个文件中的返回值

java/javascript 在线读取XML文件

javascript - 不要使用 util.inspect 记录符号

javascript - 如何模糊 iframe 弹出窗口的背景

javascript - 那么不是一个函数

Javascript Promise 循环

javascript - Promise.join() 内的条件

使用 es6-shim Promise.all() 时 typescript 打字错误