【问题标题】:how to chain multiple promises into a single transaction in Firebase如何在 Firebase 中将多个承诺链接到单个事务中
【发布时间】:2023-03-18 16:40:01
【问题描述】:

几个月前 Firebase 实施了promises in the database

在那篇博文中有一个使用带有承诺的单个事务的示例:

var article;
var articleRef = ref.child('blogposts').child(id);
articleRef.once('value').then(function(snapshot) {
  article = snapshot.val();
  return articleRef.child('readCount').transaction(function(current) {
    return (current || 0) + 1;
  });
}).then(function(readCountTxn) {
  renderBlog({
    article: article,
    readCount: readCountTxn.snapshot.val()
  });
}, function(error) {
  console.error(error);
});

是否可以将多个承诺链接到单个事务中,以便只有在所有内容都可以擦除时才能擦除数据?

【问题讨论】:

    标签: javascript firebase firebase-realtime-database


    【解决方案1】:

    您真的需要事务还是只需要原子操作?您可以同时在多个路径上执行原子操作,如果其中一个出现问题(即擦除这是一个写操作),这些操作将失败:

    var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
    
    var updatedUserData = {};
    updatedUserData["user/posts/location1"] = null;
    updatedUserData["user/blogs/location2"] = null;
    // Do a deep-path update
    ref.update(updatedUserData).then(function() {
        //yay
    }, function(error) {
        console.log("Error updating data:", error);
    });
    
    另一方面,

    事务通常用于原子数据修改,其中并发更新可能导致不一致的数据状态。想象一个点赞计数器:

    // user 1
    upvotesRef.transaction(function (current_value) {
      return (current_value || 0) + 1;
    });
    // user 2
    upvotesRef.transaction(function (current_value) {
      return (current_value || 0) + 1;
    });
    
    // upvotesRef will eventually be consistent with value += 2
    

    没有事务,您无法保证这种一致性:

    // user 1
    ref.on("value", function(snapshot) {
      console.log(snapshot.val()); // oops, could be the same value as user 2!
      ref.set(snapshot.val() + 1);
    });
    // user 2
    ref.on("value", function(snapshot) {
      console.log(snapshot.val()); // oops, could be the same value as user 1!
      ref.set(snapshot.val() + 1);
    });
    

    更多信息here

    【讨论】:

    • 哦,这很聪明,我不知道你也可以这样“删除”。
    • 今天我了解到 Pier 没有阅读我所有的答案。 :-( stackoverflow.com/questions/38084531/… ;-)
    • 不错的答案顺便说一句,汤米。不仅仅是回答问题,而是以更简单的方式解决用例。不错!
    • 谢谢弗兰克!如果您今年秋天需要实习生,请不要犹豫与我们联系 ;)
    猜你喜欢
    • 2015-07-02
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 2016-09-11
    • 2019-05-10
    • 2018-07-26
    相关资源
    最近更新 更多