Search code examples
javascriptpromisees6-promiseknex.jspg-promise

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


I have two tables "A" and "B". I want to create a row in table "B" which contains primary key of table "A" and this whole operation should be atomic.

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

Here whenever an error come at nested promise i want to reject parent promise and pass that error to parent promise.


Solution

  • I am the author of pg-promise. It has all the right ingredients for writing very clean code:

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

    You do not need to use t.batch in your example at all, and it is the best for using ES7 async.

    And if you really want to generate inserts automatically, see the helpers namespace, no need for a third-party library.