How can I make a synchronous operation with asynchronous function?
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)
output: C > A > B
expected: A > B > C
I know there is a completion block method to do so. But the requests will be nested.
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
}
}
}
A callback function executes when an asynchronous operation completes. Here is an example of how a setTimeout function works: function printMe() { console.
The simplest way to execute a method asynchronously is to start executing the method by calling the delegate's BeginInvoke method, do some work on the main thread, and then call the delegate's EndInvoke method. EndInvoke might block the calling thread because it does not return until the asynchronous call completes.
To control the spread, you might think to yourself that all you need to do is run your async functions synchronously. But this is a trap. It turns out there really is no reliable way to run an asynchronous method synchronously.
Callbacks are not asynchronous by nature, but can be used for asynchronous purposes. In this code, you define a function fn , define a function higherOrderFunction that takes a function callback as an argument, and pass fn as a callback to higherOrderFunction .
It works for me using DispatchQueue
instead.
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)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With