Skip to content

Instantly share code, notes, and snippets.

@jkereako
Last active July 29, 2025 12:55
Show Gist options
  • Save jkereako/1b5157787bc0e600674db4a8513ab924 to your computer and use it in GitHub Desktop.
Save jkereako/1b5157787bc0e600674db4a8513ab924 to your computer and use it in GitHub Desktop.
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()
@jkereako
Copy link
Author

jkereako commented Mar 1, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment