查看 Firebase API 参考文档中的此文档:https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction
以下是该文档中的代码。看看怎么样return;
用于中止事务(文档还说:“您通过不从更新函数返回值来中止事务”)。并注意这个特定情况是如何处理的onComplete()
事务完成时调用的回调函数(在else if (!committed)
{} ).
// Try to create a user for ada, but only if the user id 'ada' isn't
// already taken
var adaRef = firebase.database().ref('users/ada');
adaRef.transaction(function(currentData) {
if (currentData === null) {
return { name: { first: 'Ada', last: 'Lovelace' } };
} else {
console.log('User ada already exists.');
return; // Abort the transaction.
}
}, function(error, committed, snapshot) {
if (error) {
console.log('Transaction failed abnormally!', error);
} else if (!committed) {
console.log('We aborted the transaction (because ada already exists).');
} else {
console.log('User ada added!');
}
console.log("Ada's data: ", snapshot.val());
});
因此,恕我直言,您应该采用相同的模式,并在代码中询问“**?如何中断事务”的地方return;
.
Update:您可以使用变量来区分堕胎情况,如下所示。如果您通过 Firebase 控制台添加一个节点age
值 > 20 至users.ada.name
,第一个流产原因就会被“触发”。
var adaRef = firebase.database().ref('users/ada');
var transactionAbortionCause; //new variable
adaRef.transaction(function(currentData) {
if (currentData === null) {
return { name: { first: 'Ada', last: 'Lovelace' } };
} else if (currentData.name.age > 20) {
transactionAbortionCause = 'User ada is older than 20'; //update the variable
console.log('User ada is older than 20');
return; // Abort the transaction.
} else {
transactionAbortionCause = 'User ada already exists'; //update the variable
console.log('User ada already exists');
return; // Abort the transaction.
}
}, function(error, committed, snapshot) {
if (error) {
console.log('Transaction failed abnormally!', error);
} else if (!committed) {
console.log('We aborted the transaction because ' + transactionAbortionCause); //use the variable
} else {
console.log('User ada added!');
}
console.log("Ada's data: ", snapshot.val());
});
如果我没有记错的话,您也可以使用 Promise 来做到这一点,就像您在代码中所做的那样。文档说交易返回非空firebase.Promise
含有{committed: boolean, snapshot: nullable firebase.database.DataSnapshot}
并解释说这个承诺“可以选择用来代替onComplete
处理成功和失败的回调”。
So by:
- Doing
return;
对于您的两起堕胎案件,以及
- 读取值
committed
boolean
您应该能够通过执行以下操作来处理代码中的堕胎情况
.then((result)=>{
if (result.commited) {... } else { /*abortion!*/}
})
不过我还没有测试过这种方法