javascript - Firebase 更新值的速度没有我想要的 Javascript 快

标签 javascript firebase firebase-realtime-database

enter image description here

所以我有这个网站,它的作用就像一个统计表,当我按下 -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/

相关文章:

javascript - 在一个元素上鼠标按下?

javascript - 如何将多次出现的字符串变为一次?

javascript - 添加内容时使可滚动元素保持 "at the bottom"

java - 异常 java.lang.NoClassDefFoundError : pim

javascript - 如何验证 Firebase 安全规则中的电子邮件地址

javascript - 子元素及其父元素的鼠标滚轮处理程序

android - 如何为不同的用户设置不同的 Android Firebase 书签内容?

android-从数据库显示数据到 ListView 并每次刷新

java - 我想创建一个多用户登录我的 Android 应用程序

javascript - Firebase 启动从数据库加载与读取新添加内容