Knex 事务与 Promise [英] 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) 插入(2) 更新
(1) insert (2) update
我处理它的方法是将我的数据库操作嵌套在 .then 中.我的问题是此代码是否偶然正确?我是 promises 和 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 事务与 Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!