javascript - 如何在 Cloud Function 中重试 Cloud Firestore 事务直到状态 == true

标签 javascript firebase google-cloud-functions google-cloud-firestore

问题

我有一个 Cloud Function,它根据文档 state 字段中的更改更新 Cloud Firestore 文档。这些更新必须以特定顺序发生。当快速连续进行两项更改时,无法保证 Cloud Functions 会以正确的顺序运行。有没有办法让 Cloud Firestore 事务重试直到成功或超时?

  1. Document.state 设置为 stage1
  2. Document.state 更新为 stage2
  3. Document.state 更新为 stage3
  4. Cloud Function 被触发并读取 stage3
  5. Cloud Function 被触发并读取 stage2

在 Cloud Functions 文档中,它讨论了在失败时重试事务的能力。但是,此选项在 GCP 控制台的 Cloud Functions 部分中显示为灰色(未显示在 Firebase 控制台中)

示例代码

传入的变量

myDocumentRef: db.doc('myCollection/myDocument')
newState: stage3

交易代码

var transaction = db.runTransaction(t => {
    return t.get(myDocumentRef)
        .then(doc => {
            if ((newState = 'stage2' && doc.data().state = 'stage1') ||
                (newState = 'stage3' && doc.data().state = 'stage2')) {
              t.update(myDocumentRef, { population: newPopulation });
            } else {
              // Keep retrying the transaction until it succeeds
            }
        });
}).then(result => {
    console.log('Transaction success!');
}).catch(err => {
    console.log('Transaction failure:', err);
});

最佳答案

默认情况下,Firestore 事务会自行重试。 The documentation for transactions状态:

A transaction consists of any number of get() operations followed by any number of write operations such as set(), update(), or delete(). In the case of a concurrent edit, Cloud Firestore runs the entire transaction again. For example, if a transaction reads documents and another client modifies any of those documents, Cloud Firestore retries the transaction. This feature ensures that the transaction runs on up-to-date and consistent data.

此重试采用重复调用事务处理函数(您传递给 runTransaction 的函数)的形式。

Cloud Functions 重试机制不同。它会重试未完全成功的功能。有关其工作原理的详细信息,请阅读 here .它与 Firestore 交易无关。这些重试的语义与使用的触发器类型无关。

关于javascript - 如何在 Cloud Function 中重试 Cloud Firestore 事务直到状态 == true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48858336/

相关文章:

database - Firestore文档引用,你能扩展文档服务器端吗?

ios - 'Web' 客户端类型不允许使用自定义方案 URI - Google with Firebase

javascript - Java播放: Can't set background image in HTML/CSS

javascript - TypeError : expected bytes-like object, 不是 str

javascript - 将值传递给 Angular 2 组件

angular - 引用错误 : Can't find variable: globalThis

javascript - 获取和设置 css3 转换样式的 jQuery 插件

google-cloud-functions - 将 TensorflowJS 模型保存到 firebase 存储的最佳实践?

javascript - Cloud Spanner 无法正确管理 session 吗?

firebase - 在 Firebase Cloud Functions 中运行 Puppeteer 时遇到问题