【发布时间】:2017-12-19 13:09:23
【问题描述】:
我正在慢慢了解完成处理程序。 如果我有一个firestore查询,如果我想使用完成处理程序,我必须在firestore查询完成时使用completion()。
但它设置的功能仍然让我感到困惑。
如果这是一个以闭包为参数的函数定义:
func doSomethingAsync(completion: () -> ()) {
}
我不太明白如何从上面的 func 定义中走出来,并将其实现为真正的东西,例如 firestore 查询和请求。
query.getDocuments(){ (querySnapshot, err) in
if let err = err
{
print("Error getting documents: \(err)")
}
else
{
if(querySnapshot?.isEmpty)!
{
print("there's no document")
completion()
}
else
{
for document in querySnapshot!.documents
{
completion()
}
}
}
}
谢谢。
更新
所以对于我的例子,我可以做类似的事情
func getFirestoreData(userID: String, completion @escaping() -> ()){
//firestore code:
query.getDocuments(){ (querySnapshot, err) in
if let err = err
{
print("executed first")
completion()
}
else
.......
print("executed first")
completion()
}
}
调用我正在执行的函数:
getFirestoreData(userID: theUserID) {
print("executes second")
}
print("executes third") after function execution.
我想要发生的是编程在继续执行之前等待完成()。
但是“第三次执行”首先发生,然后是“先执行”,然后是“第二次执行”。
谢谢
【问题讨论】:
标签: swift google-cloud-firestore