Last active
July 29, 2025 12:55
-
-
Save jkereako/1b5157787bc0e600674db4a8513ab924 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
/// Synchronously wait for an asynchronous task. | |
/// | |
/// Use this is if you need to execute an asynchronous task in a synchronous | |
/// context _and_ the result from the asynchronous task is needed before | |
/// execution can proceed. | |
func synchronouslyWait(for closure: @escaping @Sendable () async -> Void, timeout: TimeInterval = 2) { | |
let group = DispatchGroup() | |
group.enter() | |
DispatchQueue.global(qos: .default).async { | |
Task { | |
await closure() | |
group.leave() | |
} | |
} | |
let _ = group.wait(timeout: .now() + .seconds(Int(timeout))) | |
} | |
func sleep(for timeInterval: TimeInterval) async throws { | |
try await Task.sleep(nanoseconds: UInt64(timeInterval * 1_000_000_000)) | |
} | |
/// Example usage | |
func synchronousContext() { | |
let interval: TimeInterval = 2 | |
let start = Date() | |
synchronouslyWait( | |
for: { try! await sleep(for: interval) }, | |
timeout: 5 | |
) | |
let end = Date() | |
let delta = start.distance(to: end) | |
assert(delta >= interval) | |
} | |
synchronousContext() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Warning!
Don't do this.
To begin with, forcing an asynchronous function to execute synchronously is bad practice. But worse than that, mixing Swift Concurrency (async/await) with GCD can lead to undefined behavior.
Description
I found myself needing to execute an asynchronous task in a synchronous context and I had to wait until the asynchronous task completed before execution could continue. This is one way to handle that scenario.
Know that this is bad practice. But also know creativity doesn't necessarily follow the rules.