我的问题是有关Firebase实时数据库事务中发生的事情。假设我在云函数中有与此类似的代码。导出的函数由http请求调用。好的,我知道应该在诺言返回后调用updateBalance()
,但这不是重点。我想知道的是为什么,如果我要执行该代码,使余额为25.00,则在hasMoneyInTheBank()中调用ref.once()返回的值是-0.02,而不是25.00或24.98。
我知道最终所有内容都会更新,最终值为24.98。是因为我正在从同一连接读取数据吗?
如果其他进程此时会读取相同的数据怎么办?
function updateBalance(id, amount){
const db = database();
const currentBalance = db.ref(`${id}/balance`);
currentBalance.transaction(currentValue =>(currentValue*100 - amount*100)/100 );
}
function hasMoneyInTheBank(id,amount){
const db = database();
const ref = db.ref(`${id}/balance`);
ref.once('value',snap => {
console.log(`This is the balance:${snap.val()}`);
if(snap.val() > amount){
return true;
}else{
return false;
}
})
.catch(error=> console.log(error));
}
export function doSomeAction(id, description){
const db = database();
const ref = db.ref(`${id}/logs/log_something`);
const data = {timestamp:database.ServerValue.TIMESTAMP, description:description};
ref.push();
console.log(hasMoneyInTheBank is: ${hasMoneyInTheBank(id,5.00)}`);
updateBalance(id,0.02);
};