Skip to content

Instantly share code, notes, and snippets.

@mattcomi
Created October 31, 2025 02:51
Show Gist options
  • Select an option

  • Save mattcomi/fd473e9b7e7d7d4cb3665b6b52abc07d to your computer and use it in GitHub Desktop.

Select an option

Save mattcomi/fd473e9b7e7d7d4cb3665b6b52abc07d to your computer and use it in GitHub Desktop.
Timeout on await
import Foundation
class Downloader {
static var shared = Downloader()
public func download() async throws -> Data {
// All your logic around returning a cached result, starting a task or await an existing task goes here, as normal.
try await Task.sleep(for: .seconds(5))
print("Download complete")
return Data()
}
private init() {}
}
@main
struct Main {
static func timeoutWaitForDownload() async -> Data? {
var sleepTask: Task<Void, Error>?
var result: Data?
sleepTask = Task {
try await Task.sleep(for: .seconds(1))
}
Task {
result = try await Downloader.shared.download()
sleepTask?.cancel()
}
do {
try await sleepTask?.value
} catch {
// timeout
}
return result
}
static func main() async throws {
let data = await timeoutWaitForDownload()
// for the demo. If timeout occurred before download, the application will exit before the download is complete.
try await Task.sleep(for: .seconds(10))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment