如何使用异步函数进行同步操作?
class MyClass {
static let shared = MyClass()
let operationQueue = OperationQueue()
let dispatchGroup = DispatchGroup()
func request(_ myRequestURL: URL) {
operationQueue.addOperation {
self.dispatchGroup.enter()
// Async function
Alamofire.request(myRequestURL).response { response in
print(response.request)
self.dispatchGroup.leave()
}
self.dispatchGroup.wait(timeout: .distantFuture)
}
}
}
MyClass.shared.request(A)
MyClass.shared.request(B)
MyClass.shared.request(C)
输出:C> A>乙
预期:A> B> ç
我知道有一个完成块方法可以这样做。但请求将嵌套。
func request(_ myRequestURL: URL, completion: @escaping (_ data: Data?) -> Void) {
// Async function
Alamofire.request(myRequestURL).response { response in
completion(response.data)
}
}
MyClass.shared.request(A){_ in MyClass.shared.request(B){_ in MyClass.shared.request(C){_ in } } }
答案 0 :(得分:8)
使用DispatchQueue
代替我。
class MyClass {
static let shared = MyClass()
let dispatchQueue = DispatchQueue(label: "ALAMOFIRE_REQUEST")
let dispatchGroup = DispatchGroup()
func request(_ myRequestURL: URL) {
dispatchQueue.async {
self.dispatchGroup.enter()
// Async function
Alamofire.request(myRequestURL).response { response in
print(response.request)
self.dispatchGroup.leave()
}
self.dispatchGroup.wait(timeout: .distantFuture)
}
}
}