2016-11-20 128 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()沒有趕上()