Home > Software engineering >  Is it possible to not declare function as async and still run an async operation in it which will re
Is it possible to not declare function as async and still run an async operation in it which will re

Time:10-21

I'm currently re-writing a lot of code to use new async/await mechanism, but I want to do it piece by piece instead of changing every file in my project to use async/await.

How would I go about converting method that used completion handler, like this:

func fetchLibrary(completion: ((Error?) -> Void)?) {
    apiManager.loadLibraryContent { [weak self] result in
        switch result {
        case .success(let records):
            let databaseError = self?.databaseManager.updateDatabase(withNewRecords: records)
            completion?(databaseError)
        case .failure(let error):
            completion?(error)
        }
    }
}

Then update the loadLibraryContent method of apiManager to look like this:

func loadLibraryContent() async throws -> [GRDBRecord] {

And still be able use the completion handler in the first method? It would make gradual migration to async/await easier.

Ideally the new code would look something like this:

func fetchLibrary(completion: ((Error?) -> Void)?) {
    do {
        let records = try await apiManager.loadLibraryContent()
        let databaseError = self?.databaseManager.updateDatabase(withNewRecords: records)
        completion?(databaseError)
    } catch {
        completion?(error)
    }
}

Is it possible to do in Swift?

CodePudding user response:

You can use Task

    func fetchLibrary(completion: ((Error?) -> Void)?) {
        Task {
            do {
                let records = try await apiManager.loadLibraryContent()
                let databaseError = self?.databaseManager.updateDatabase(withNewRecords: records)
                completion?(databaseError)
            } catch {
                completion?(error)
            }
        }
    }
  • Related