我有嵌套的异步任务。此流程后面的函数:loadEpisodes(加载剧集列表) - >使用完成后的数组循环每个第一集并为特定剧集加载评论(另外一个异步任务)。
问题是:在完成注释加载任务之前执行了comletion(fullyEpisodes)。我试图使用Dispatch Group(第二个代码块),但它没有工作。
func loadComments(comletion: @escaping ([Episode]) -> Void){
loadEpisodes(completion: {
episodes in
var fullyEpisodes = [Episode]()
for episode in episodes {
WebService().load(resource: episode.comment, comletion: {
comments in
if let comments = comments {
let _episode = Episode(id: episode.id, title: episode.title, comments: comments)
fullyEpisodes.append(_episode)
print("done")
}
})
}
comletion(fullyEpisodes)
})
}
已实施调度组:
func loadComments(comletion: @escaping ([Episode]) -> Void){
loadEpisodes(completion: {
episodes in
var fullyEpisodes = [Episode]()
let group = DispatchGroup()
for episode in episodes {
group.enter()
WebService().load(resource: episode.comment, comletion: {
comments in
if let comments = comments {
let _episode = Episode(id: episode.id, title: episode.title, comments: comments)
fullyEpisodes.append(_episode)
print("done")
}
})
group.leave()
}
group.wait()
group.notify(queue: .main, execute: {
comletion(fullyEpisodes)
})
})
}
当我尝试用" print("某些")"替换注释加载请求时(不是新的异步任务),Dispatch组正在运行。
答案 0 :(得分:5)
在你的第二个例子中,(a)将group.leave()
移动到load()
完成处理程序闭包中; (b)完全删除group.wait()
。
func loadComments(comletion: @escaping ([Episode]) -> Void){
loadEpisodes(completion: {
episodes in
var fullyEpisodes = [Episode]()
let group = DispatchGroup()
for episode in episodes {
group.enter()
WebService().load(resource: episode.comment, comletion: {
comments in
if let comments = comments {
let _episode = Episode(id: episode.id, title: episode.title, comments: comments)
fullyEpisodes.append(_episode)
print("done")
}
group.leave()
})
// group.leave()
}
//group.wait()
group.notify(queue: .main, execute: {
comletion(fullyEpisodes)
})
})
}
或者,使用尾随闭包语法清理一下并修复completion
拼写:
func loadComments(completion: @escaping ([Episode]) -> Void) {
loadEpisodes { episodes in
var fullyEpisodes = [Episode]()
let group = DispatchGroup()
for episode in episodes {
group.enter()
WebService().load(resource: episode.comment) { comments in
if let comments = comments {
let _episode = Episode(id: episode.id, title: episode.title, comments: comments)
fullyEpisodes.append(_episode)
}
group.leave()
}
}
group.notify(queue: .main) {
completion(fullyEpisodes)
}
}
}