【发布时间】:2020-07-30 01:15:33
【问题描述】:
所以,这是我的代码,它非常简单...只是尝试检查具有特定名称的文档是否存在于我的 firestore 集合中并返回一个布尔值作为其状态:
func checkSessionCode(_ code: String) -> Bool {
print("checkSessionCode running")
var doesCodeExist = false
let docRef = env.db.collection(K.sessions).document(code)
docRef.getDocument { (document, error) in
if document!.exists {
print("Document data: \(document!.data())")
doesCodeExist = true
} else {
print("Document does not exist")
doesCodeExist = false
}
}
print("doesCodeExist == \(doesCodeExist)")
return doesCodeExist
}
长话短说,无论我的输入代码是什么(如果它与文档匹配),它总是返回 false。此外,对于它的价值,在控制台中 print("doesCodeExist == (doesCodeExist)") 输出总是在 print("Document data: (document!.data())") 之前打印...有什么关于这个闭包是在它完成检查服务器之前返回值吗?
另外,我的文档非常轻量级,所以检查速度很快(显然不够快)...
【问题讨论】:
-
"...这个闭包在完成检查服务器之前是否返回了值?"关闭不返回任何东西。它通过副作用而不是返回来设置值
doesCodeExist。您看到的是副作用不会及时发生,因为它是异步运行的。搜索“return from async swift”,你会看到这个问题已经被问了几千次了
标签: swift google-cloud-firestore