How to call async throwing functions
How to call async throwing functions êŽë š
Updated for Xcode 15
Just like their synchronous counterparts, Swiftâs async functions can be throwing or non-throwing depending on how you want them to behave. However, there is a twist: although we mark the function as being async throws
, we call the function using try await
â the keyword order is flipped.
To demonstrate this in action, hereâs a fetchFavorites()
method that attempts to download some JSON from my server, decode it into an array of integers, and return the result:
func fetchFavorites() async throws -> [Int] {
let url = URL(string: "https://hws.dev/user-favorites.json")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode([Int].self, from: data)
}
if let favorites = try? await fetchFavorites() {
print("Fetched \(favorites.count) favorites.")
} else {
print("Failed to fetch favorites.")
}
Both fetching data and decoding it are throwing functions, so we need to use try
in both those places. Those errors arenât being handled in the function, so we need to mark fetchFavorites()
as also being throwing so Swift can let any errors bubble up to whatever called it.
Notice that the function is marked async throws
but the function calls are marked try await
â like I said, the keyword order gets reversed. So, itâs âasynchronous, throwingâ in the function definition, but âthrowing, asynchronousâ at the call site. Think of it as unwinding a stack.
Not only does try await
read more easily than await try
, but itâs also more reflective of whatâs actually happening when our code executes: weâre waiting for some work to complete, and when it does complete weâll check whether it ended up throwing an error or not.
Of course, the other possibility is that they could have try await
at the call site and throws async
on the function definition, and hereâs what the Swift team says about that:
âThis order restriction is arbitrary, but it's not harmful, and it eliminates the potential for stylistic debates.â
Personally, if I saw throws async
Iâd be more likely to write it as âthis thing throws an async errorâ or similar, but as the quote above says ultimately the order is just arbitrary.