我正在运行一个非常简单的 Firestore 事务,该事务会检查文档是否存在,如果不存在则写入它。
(用例正在注册用户名 - 如果尚未注册,则当前用户可以获取它)
以下是相关 Flutter 代码的片段:
DocumentReference usernameDocRef =
Firestore.instance.collection(_USERNAMES).document(username);
await Firestore.instance.runTransaction((transaction) async {
var snapshot = await transaction.get(usernameDocRef);
if (!snapshot.exists) {
transaction.set(usernameDocRef, {
_UsernamesKey.userid: _user.id,
});
}
});
这失败了,出现“事务所有重试失败”异常。
基于 Firestore documentation , 失败可能有两个原因:
- The transaction contains read operations after write operations. Read operations must always come before any write operations.
- The transaction read a document that was modified outside of the transaction. In this case, the transaction automatically runs again. The transaction is retried a finite number of times.
我认为我不会触发其中任何一个。有什么建议吗?
最佳答案
example transaction in the documentation在调用 update
时使用 await
。也许你在调用 set
时需要同样的:
await Firestore.instance.runTransaction((transaction) async {
var snapshot = await transaction.get(usernameDocRef);
if (!snapshot.exists) {
await transaction.set(usernameDocRef, {
_UsernamesKey.userid: _user.id,
});
}
});
关于firebase - Firestore 事务失败,出现 "Transaction failed all retries",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50975938/