问题
我有一个 Cloud Function,它根据文档 state
字段中的更改更新 Cloud Firestore 文档。这些更新必须以特定顺序发生。当快速连续进行两项更改时,无法保证 Cloud Functions 会以正确的顺序运行。有没有办法让 Cloud Firestore 事务重试直到成功或超时?
Document.state
设置为stage1
Document.state
更新为stage2
Document.state
更新为stage3
- Cloud Function 被触发并读取
stage3
- 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/