2016-11-20 129 views
2

我有两个表“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); 
    }); 
} 

在这里每当一个错误发生在嵌套承诺我想拒绝父承诺并将该错误传递给父承诺。

+0

除非你在孩子'catch()'中做了任何有建设性的事情,否则只要将它移除并且只要你继续返回承诺但你还需要在't.one'中返回't.none' – charlietfl

+0

@charlietfl我试过了,但没有成功收到错误“未处理的承诺拒绝”。 – Naresh

+0

在你的交易中使用't.batch'完全没有意义。 'pg-promise'拥有自己的,甚至更强大的支持来生成插入和更新,你也不需要使用'knex'。 –

回答

1

我的pg-promise笔者返回承诺。它拥有所有编写非常干净的代码正确的成分:

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

你并不需要在您的示例使用t.batch可言的,它是最好的使用ES6发电机。

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

0

得到它的工作....不得不从孩子父母是t.none()没有赶上()