所以我有这个网站,它的作用就像一个统计表,当我按下 -1 按钮时,游戏的分数会下降 1。我使用 javascript 访问 firebase 数据库,然后将分数减去1.
const docRef = doc(db, "Games", game_id);
const docSnap = await getDoc(docRef);
var score = docSnap.data().team2_score
await updateDoc(docRef, {
team2_score: score -= number
});
问题是,如果用户多次快速点击它,Firebase 就不会执行所有这些操作。因此,如果用户快速单击按钮 5 次,Firebase 数据库将仅跟踪其中 4 次。这是我的问题。
有没有一种方法可以确保数据库中的每一次点击都会更新,即使点击速度非常快?
最佳答案
您有两个选择:
选项 1
使用 Firebase 增量:https://cloud.google.com/firestore/docs/samples/firestore-data-set-numeric-increment
const docRef = doc(db, "Games", game_id);
await updateDoc(docRef, {
team2_score: firebase.firestore.FieldValue.increment(-1)
});
选项 2
使用事务。 https://firebase.google.com/docs/firestore/manage-data/transactions#transactions
const docRef = doc(db, "Games", game_id);
try {
const result = await db.runTransaction((transaction) => {
// This code may get re-run multiple times if there are conflicts.
return transaction.get(docRef).then((sfDoc) => {
if (!sfDoc.exists) {
throw "Document does not exist!";
}
// Note: this could be done without a transaction
// by updating the score using FieldValue.increment()
var newScore= sfDoc.data().team2_score - 1;
transaction.update(docRef, { team2_score: newScore});
});
})
console.log("Transaction successfully committed!");
} catch(error) {
console.log("Transaction failed: ", error);
}
关于javascript - Firebase 更新值的速度没有我想要的 Javascript 快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75404554/