I would like to simulate async and await request from Javascript to Swift 4. I searched a lot on how to do it, and I thought I found the answer with DispatchQueue
, but I don't understand how it works.
I want to do a simple stuff:
if let items = result.value { var availableBornes = [MGLPointFeature]() for item in items { guard let id = item.id else { continue } let coordinate = CLLocationCoordinate2D(latitude: Double(coor.x), longitude: Double(coor.y)) // ... // This is an asynchronous request I want to wait await _ = directions.calculate(options) { (waypoints, routes, error) in guard error == nil else { print("Error calculating directions: \(error!)") return } // ... if let route = routes?.first { let distanceFormatter = LengthFormatter() let formattedDistance = distanceFormatter.string(fromMeters: route.distance) item.distance = formattedDistance // Save feature let feature = MGLPointFeature() feature.attributes = [ "id": id, "distance": formattedDistance ] availableBornes.append(feature) } } } // This should be called after waiting for the async requests self.addItemsToMap(availableBornes: availableBornes) }
What should I do?
Swift now supports asynchronous functions — a pattern commonly known as async/await. Discover how the new syntax can make your code easier to read and understand. Learn what happens when a function suspends, and find out how to adapt existing completion handlers to asynchronous functions.
Calling an asynchronous function with await runs only one piece of code at a time. While the asynchronous code is running, the caller waits for that code to finish before moving on to run the next line of code.
Although Swift functions are synchronous by default, we can make them asynchronous by adding one keyword: async . Inside asynchronous functions, we can call other asynchronous functions using a second keyword: await . As a result, you'll often hear Swift developers talk about async/await as a way of coding.
async: Indicates that a method or function is asynchronous. Using it lets you suspend execution until an asynchronous method returns a result. await: Indicates that your code might pause its execution while it waits for an async -annotated method or function to return.
Thanks to vadian's comment, I found what I expected, and it's pretty easy. I use DispatchGroup()
, group.enter()
, group.leave()
and group.notify(queue: .main){}
.
func myFunction() { let array = [Object]() let group = DispatchGroup() // initialize array.forEach { obj in // Here is an example of an asynchronous request which use a callback group.enter() // wait LogoRequest.init().downloadImage(url: obj.url) { (data) in if (data) { group.leave() // continue the loop } } } group.notify(queue: .main) { // do something here when loop finished } }
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