【发布时间】:2020-06-12 19:31:49
【问题描述】:
简介
你好,
我正在尝试从 mongoose withTransaction 回调传递数据。现在,我正在使用以下实现回调的代码:
const transactionSession = await mongoose.startSession()
await transactionSession.withTransaction(async (tSession) => {
try {
// MARK Transaction writes & reads removed for brevity
console.log("Successfully performed transaction!")
cb(null, "Any test data")
return Promise.resolve()
} catch (error) {
console.log("Transaction aborted due to error:", error)
cb(error)
return Promise.reject()
}
})
} catch (error) {
console.log(error)
return cb(error)
}
可以找到here 使用的withTransaction 助手的更详细的sn-p。
可以在 here 找到有关 withTransaction 助手的官方 Mongoose 文档的链接。
目前,我正在使用回调从withTransactioncallback 传递数据:
cb(null, "Any test data")
但是,问题在于,在返回 Promise.resolve() 之前,自然会先执行回调。这意味着,(在我的情况下)在提交任何必要的数据库写入之前将成功响应发送回客户端:
// this is executed first - the callback will send back a response to the client
cb(null, "Any test data")
// only now, after the response already got sent to the client, the transaction is committed.
return Promise.resolve()
为什么我认为这是个问题:
老实说,我不确定。如果当时没有任何数据库写入,那么将成功响应发送回客户端是不合适的。有人知道处理这个特定用例的适当方法吗?
我考虑过使用类似这样的方法将数据从 withTransaction 助手中传递出来:
const transactionResult = await transactionSession.withTransaction({...})
我试过了,响应是 MongoDB 的 CommandResult,其中不包括我在已解决的承诺中包含的任何数据。
总结
如果在提交事务之前将成功响应发送回客户端,是否有问题?如果是这样,从withTransaction 助手传递数据并因此在发送回响应之前提交事务的适当方法是什么?
如果我得到任何建议,我将不胜感激。
【问题讨论】:
标签: javascript node.js mongodb mongoose async-await