如何使用异步回调进行同步操作?
问题描述:
如何使用异步功能进行同步操作?如何使用异步回调进行同步操作?
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> B
预期:A> B> C
我知道有一个完成块的方法来这样做。但是请求将被嵌套。
func request(_ myRequestURL: URL, completion: @escaping (_ data: Data?) -> Void) {
// Async function
Alamofire.request(myRequestURL).response { response in
completion(response.data)
}
}
MyClass.shared.request(A){_在
MyClass.shared.request(B){_在
MyClass.shared .request(C){_
}
}
}
答
它的工作原理我使用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)
}
}
}
的可能的复制[链的多个Alamofire请求(http://*.com/questions/28634995/chain-multiple-alamofire-requests) – kennytm
让你的队列串行:'operationQueue.maxConcurrentOperationCount = 1' – shallowThought
是的。它像JavaScript中的[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)。我如何用GCD以Swifty的方式做? – WeiJay