提交 bf99f0a9 编写于 作者: 雪洛's avatar 雪洛

docs: transaction

上级 2bd0f4af
...@@ -1501,23 +1501,28 @@ exports.main = async (event) => { ...@@ -1501,23 +1501,28 @@ exports.main = async (event) => {
const bbbRes = await transaction.collection('account').doc('bbb').get() const bbbRes = await transaction.collection('account').doc('bbb').get()
if (aaaRes.data && bbbRes.data) { if (aaaRes.data && bbbRes.data) {
const updateAAARes = await transaction.collection('account').doc('aaa').update({ try {
data: { const updateAAARes = await transaction.collection('account').doc('aaa').update({
amount: _.inc(-10) data: {
} amount: _.inc(-10)
}) }
})
const updateBBBRes = await transaction.collection('account').doc('bbb').update({ const updateBBBRes = await transaction.collection('account').doc('bbb').update({
data: { data: {
amount: _.inc(10) amount: _.inc(10)
} }
}) })
console.log(`transaction succeeded`) console.log(`transaction succeeded`)
// 会作为 runTransaction resolve 的结果返回 // 会作为 runTransaction resolve 的结果返回
return { return {
aaaAccount: aaaRes.data.amount - 10, aaaAccount: aaaRes.data.amount - 10,
}
} catch(e) {
// 会作为 runTransaction reject 的结果出去
await transaction.rollback(-100)
} }
} else { } else {
// 会作为 runTransaction reject 的结果出去 // 会作为 runTransaction reject 的结果出去
...@@ -1568,8 +1573,8 @@ const db = uniCloud.database() ...@@ -1568,8 +1573,8 @@ const db = uniCloud.database()
const _ = db.command const _ = db.command
exports.main = async (event) => { exports.main = async (event) => {
const transaction = await db.startTransaction()
try { try {
const transaction = await db.startTransaction()
const aaaRes = await transaction.collection('account').doc('aaa').get() const aaaRes = await transaction.collection('account').doc('aaa').get()
const bbbRes = await transaction.collection('account').doc('bbb').get() const bbbRes = await transaction.collection('account').doc('bbb').get()
...@@ -1596,7 +1601,6 @@ exports.main = async (event) => { ...@@ -1596,7 +1601,6 @@ exports.main = async (event) => {
aaaAccount: aaaRes.data.amount - 10, aaaAccount: aaaRes.data.amount - 10,
} }
} else { } else {
await transaction.rollback()
return { return {
success: false, success: false,
...@@ -1605,6 +1609,7 @@ exports.main = async (event) => { ...@@ -1605,6 +1609,7 @@ exports.main = async (event) => {
} }
} }
} catch (e) { } catch (e) {
await transaction.rollback()
console.error(`transaction error`, e) console.error(`transaction error`, e)
return { return {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册