Knex事务与承诺 [英] Knex Transaction with Promises
问题描述
我得到了正确的输出,确实,这两个操作被当作一个事务单元;
I am getting the correct output, and indeed, these two operations are being treated as a single transactional unit; where if one fails, both fail.
在此代码示例中:我正在执行
In this code example: i am doing a transaction of
的事务1)insert
(2)update
(1) insert (2) update
我的方法是将我的db操作嵌入.then。
我的问题是如果这个代码是正确的意外?我是一个新的承诺和knex。
The way I approach it is to nest my db operations inside the .then. My question is if this code is correct by accident? i am new to promises and knex.
knex.transaction(function(t) {
knex('foo')
.transacting(t)
.insert({id:"asdfk", username:"barry", email:"barry@bar.com"})
.then(function() {
knex('foo')
.where('username','=','bob')
.update({email:"bob@foo.com"})
.then(t.commit, t.rollback)
})
})
.then(function() {
// it worked
},
function() {
// it failed
});
这可行,但我觉得我做错了。寻找评论。
This works, but I feel like I am doing something wrong still. Looking for comments.
推荐答案
您需要从内部查询返回一个promise以便外链链接。
You need to return a promise from the inner query in order for the outer chain to be chained with that.
您也可以忽略任何错误,因为您不要重新抛出它们 - 最好使用 .catch()
因为它使得更清楚发生了什么 - 这是正常的 try-catch
语句会发生什么。
You also swallow any errors because you don't rethrow them - it's better to use .catch()
for this reason because it makes it more clearer what is happening - that is what would happen with normal try-catch
statement.
knex.transaction(function(t) {
return knex('foo')
.transacting(t)
.insert({id:"asdfk", username:"barry", email:"barry@bar.com"})
.then(function() {
return knex('foo')
.where('username','=','bob')
.update({email:"bob@foo.com"});
})
.then(t.commit)
.catch(function(e) {
t.rollback();
throw e;
})
})
.then(function() {
// it worked
})
.catch(function(e) {
// it failed
});
为了更好地理解它,这里是被仿真的同步版本:
To understand it better, here's the synchronous version that is being "emulated":
try {
var t = knex.transaction();
try {
knex("foo")
.transacting(t)
.insert({id:"asdfk", username:"barry", email:"barry@bar.com"});
knex("foo")
.where('username','=','bob')
.update({email:"bob@foo.com"});
t.commit();
}
catch (e) {
t.rollback();
// As you can see, if you don't rethrow here
// the outer catch is never triggered
throw e;
}
// It worked
}
catch (e) {
//It failed
}
这篇关于Knex事务与承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!