如何处理多次写入,以便如果一次写入失败,则不会提交数据? [英] How to treat multiple writes so that if one write fails, the data isn't committed?

查看:74
本文介绍了如何处理多次写入,以便如果一次写入失败,则不会提交数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Firebase实时数据库中,我需要将child_node1添加到node1,然后紧接着将child_node2添加到node2,该信息是相关的.

In Firebase Realtime Database, let's say that I need to add a child_node1 to node1 and, immediately after that, a child_node2 to node2, the information being related.

我可以轻松地在插入第一个子节点的完成处理程序中添加第二个子节点.但是,如果用户恰好在第二次通话期间关闭了该应用程序,该怎么办?还是网络突然掉线了?

I could easily add the second child node in the completion handler of the insertion of the first child node. But what if the user closes the app exactly during the second call? Or the network suddenly goes down?

当且仅当两个调用(事务)均成功时,我如何才能确保提交信息?

How should I make sure that the information gets committed if and only if both calls (transactions) succeed?

例如,在主节点(users)中创建用户后,我还要根据其位置将其添加到另一个名为users-locations的节点中.如果在添加users之后但没有完成添加users-locations之前发生错误怎么办?

For example, after creating a user in the main node (users), I want to also add him in another node called users-locations according to his location. What if an error occurs after adding in users but before finishing adding in users-locations?

谢谢!

推荐答案

您要尝试的是扇出操作,正如Doug所说,您通常希望通过单个多位置更新来完成此操作.多位置更新的规模比交易要好得多.

What you're trying to do is a fan-out operation, and as Doug commented you'll typically want to do this with a single multi-location update. Multi-location updates scale much better than transactions.

例如,一次写入两个位置:

For example, to write to both locations at once you'd do:

let updates = ["/node1/child_node1": "value", "/node2/child_node2": "value"]

ref.updateChildValues(updates)

一些用于阅读有关这些内容的好资料是:

Some great sources for reading more about these are:

  • the blog post introducing multi-location updates
  • the blog post discussing using multi-location updates for fan-out operations
  • my answer on strategies for data consistency with denormalized data
  • Andrew's answer on a similar topic
  • an answer showing how to do multi-location deletes
  • many other questions mentioning multi-location updates

这篇关于如何处理多次写入,以便如果一次写入失败,则不会提交数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆