如何检查两个异步任务是否成功完成 [英] How to check if two asynchronous tasks are done with success
本文介绍了如何检查两个异步任务是否成功完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在函数中实现此流程图的最佳和最简便的方法是什么? 现在,我正在使用两个调度组,但是我需要检查它们是否都已完成,而不仅是在完成时.
What is the best and easiest way to implement this flowchart in a function? Right now I'm using two dispatch groups but I need to check if they're both done, and not only when they finish.
如果完成,那么:
- friends数组将包含元素
- 昵称数组将包含元素
注意:FB是Facebook,FIR是Firebase数据库
note: FB is Facebook and FIR is Firebase database
推荐答案
您可以使用DispatchGroup
进行此操作.尝试以下游乐场;
You could do this using DispatchGroup
. Try the following playground;
import UIKit
import XCPlayground
let dispatchGroup = DispatchGroup.init()
for index in 0...4 {
dispatchGroup.enter()
let random = drand48()
let deadline = DispatchTime.now() + random/1000
print("entered \(index)")
DispatchQueue.global(qos: .background).asyncAfter(deadline: deadline, execute: {
print("leaving \(index)")
dispatchGroup.leave()
})
}
dispatchGroup.notify(queue: .global()) {
print("finished all")
}
应该输出类似于
entered 0
leaving 0
entered 1
entered 2
leaving 1
leaving 2
entered 3
leaving 3
entered 4
leaving 4
finished all
这篇关于如何检查两个异步任务是否成功完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文