【发布时间】:2019-05-25 09:09:02
【问题描述】:
我正在创建一个database 事务,其中包含多个插入。结果保存为 Future 的 array。然后我在寻找do{..}.catch{..}构造中的运算结果。这是
问题:如果我从 do 块返回失败的未来,那么所有事务都会回滚 - 很好,但如果我从“catch”块返回相同的失败未来,那么一些记录正在提交到数据库。
func save(on req: Request) -> Future<Confirmation>
{
return req.transaction(on: .psql) { conn in
let promise = conn.eventLoop.newPromise(Confirmation.self)
var futures = [Future<Bool>]()
for i in 0 ..< 20
{
let g1 = Group()
g1.name = "\(i)"
let f1 = g1.save(on: conn).then { _ -> Future<Bool> in
if i == 15
{
// return conn.eventLoop.newSucceededFuture(result: false) //1
return conn.eventLoop.newFailedFuture(error: SyncError.nullPrimaryKey) // 2
}
else
{
return conn.eventLoop.newSucceededFuture(result: true)
}
}
futures.append(f1)
}
futures.do(on: conn){ results in
var res = true
results.forEach { e in
res = res && e
}
if res {
promise.succeed(result: Confirmation())
}
else {
promise.fail(error: SyncError.nullPrimaryKey) // 3
}
}.catch { e in
promise.fail(error: e) // 4
}
return promise.futureResult
}
}
}
在此示例中,promise 在第 4 行(块 catch)中实现了失败,并且我遇到了未还原事务的问题。 但是,如果我注释掉第 1 行并取消注释第 2 行,那么 promise 在第 3 行中实现(块 do),并且整个事务被正确还原。
是我代码某处的错,还是 Fluent 错误?
【问题讨论】: