使用具有多个异步调用的调度队列
Using dispatch queues with multiple async calls
我有一个带有完成处理程序的函数,并且在函数中我正在进行 2 个独立的异步调用。
它的伪像:
func Foo(completion: ()->()) {
let dispatchGroup = DispatchGroup()
for doc in documents {
dispatchGroup.enter()
ref.getDocument(completion: { (snapshot, error) in
//Need another getDocument call here
let Object = Object(init with snapshot data)
dispatchGroup.leave()
}
}
} completion()
我需要做的是在我添加评论的地方添加另一个异步调用。
这将使代码看起来像:
ref.getDocument(completion: { (snapshot, error) in
userCountRef.getDocuments(completion: { (snap, error) in
let Object = Object(init with snapshot data)
dispatchGroup.leave()
}
} completion()
第二组代码的问题是我的完成处理程序在我的 for 循环第一次通过后被调用。
基本上我想要做的是能够用一个调度组处理两组异步调用。我需要关闭第一个电话,然后根据第一个电话的信息,我需要用它来进行第二个电话,然后最后制作一个 class 对象,循环完全冲洗和重复,然后然后在最后叫我完成。
如何实现?
当第二个异步调用依赖于第一个,但没有来自 ref
内任何其他对象的其他第一个数据调用时,这应该有效:
func Foo(completion: ()->()) {
let dispatchGroup = DispatchGroup()
for doc in documents {
dispatchGroup.enter()
ref.getDocument(completion: { (snapshot, error) in
userCountRef.getDocuments(completion: { (snap, error) in
let Object = Object(init with snapshot data)
dispatchGroup.leave()
}
}
}
// .main here is the main DispatchQueue. Can be any queue desired
dispatchGroup.notify(.main) {
completion()
}
}
此 notify
将确保所有 enter
在调用您的 completion
之前都已通过结束 leave
匹配。在苹果文档中查看更多信息 here.
我有一个带有完成处理程序的函数,并且在函数中我正在进行 2 个独立的异步调用。
它的伪像:
func Foo(completion: ()->()) {
let dispatchGroup = DispatchGroup()
for doc in documents {
dispatchGroup.enter()
ref.getDocument(completion: { (snapshot, error) in
//Need another getDocument call here
let Object = Object(init with snapshot data)
dispatchGroup.leave()
}
}
} completion()
我需要做的是在我添加评论的地方添加另一个异步调用。
这将使代码看起来像:
ref.getDocument(completion: { (snapshot, error) in
userCountRef.getDocuments(completion: { (snap, error) in
let Object = Object(init with snapshot data)
dispatchGroup.leave()
}
} completion()
第二组代码的问题是我的完成处理程序在我的 for 循环第一次通过后被调用。
基本上我想要做的是能够用一个调度组处理两组异步调用。我需要关闭第一个电话,然后根据第一个电话的信息,我需要用它来进行第二个电话,然后最后制作一个 class 对象,循环完全冲洗和重复,然后然后在最后叫我完成。
如何实现?
当第二个异步调用依赖于第一个,但没有来自 ref
内任何其他对象的其他第一个数据调用时,这应该有效:
func Foo(completion: ()->()) {
let dispatchGroup = DispatchGroup()
for doc in documents {
dispatchGroup.enter()
ref.getDocument(completion: { (snapshot, error) in
userCountRef.getDocuments(completion: { (snap, error) in
let Object = Object(init with snapshot data)
dispatchGroup.leave()
}
}
}
// .main here is the main DispatchQueue. Can be any queue desired
dispatchGroup.notify(.main) {
completion()
}
}
此 notify
将确保所有 enter
在调用您的 completion
之前都已通过结束 leave
匹配。在苹果文档中查看更多信息 here.