I would like to convert a sync function to an async function, but I don't know what is the correct way to do it.
Let assume I have a sync function that take a long time to get data:
func syncLongTimeFunction() throws -> Data { Data() }
Then I called it in the below function, it is still a sync function.
func syncGetData() throws -> Data {
return try syncLongTimeFunction()
}
But now I would like to convert it to async function. What is the correct way below:
First way:
func asyncGetData() async throws -> Data { return try syncLongTimeFunction() }
Second way:
func asyncGetData2() async throws -> Data { return try await withCheckedThrowingContinuation { continuation in DispatchQueue.global().async { do { let data = try self.syncLongTimeFunction() continuation.resume(returning: data) } catch { continuation.resume(throwing: error) } } } }
I thought the first way is enough, like Rob has answer below. But when I call the async function like below on main thread, the syncLongTimeFunction()
is processed on main thread as well. So it will block the main thread.
async {
let data = try? await asyncGetData()
}