简体   繁体   中英

Swift: can I use async/await syntax with a function that already returns synchronously a value?

I know that I can use async/await to replace this:

func test(_ completion: @escaping (Int) -> Void) {
    // ...
    completion(foundValue)
}

with this:

func test async -> Int {
    let result = await calculate()
    return result
}

However, can I do something if the initial function is like this?

func test(_ completion: @escaping (Int) -> Void) -> Int {
    // ...
}

Thank you for your help

If your function doesn't need to wait for completion handler call then you can create a top level task and call your completion handler from the task after doing asynchronous work:

func test(_ completion: @escaping (Int) -> Void) -> Int {
    // synhronous calls
    Task {
        // async funtion calls
        completion(value)
    }
    return value
}

If you need to wait for all your asynchronous task completion before returning, you can use a semaphore for that:

func test(_ completion: @escaping (Int) -> Void) -> Int {
    let semaphore = DispatchSemaphore(value: 0)
    // synhronous calls
    Task {
        // async funtion calls
        completion(value)
        // signal async task completion
        semaphore.signal()
    }
    // wait for async task completion
    semaphore.wait()
    return value
}

Note that using semaphore.wait() blocks the current thread and blocking the thread can cause undefined runtime behaviors in modern concurrency. So proceed with caution when using such approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM