Skip to content

Instantly share code, notes, and snippets.

@finestructure
Last active August 5, 2024 01:34
Show Gist options
  • Save finestructure/500d9fda7dfc99400e8ef5bddb38776b to your computer and use it in GitHub Desktop.
Save finestructure/500d9fda7dfc99400e8ef5bddb38776b to your computer and use it in GitHub Desktop.
Async defer
@discardableResult
func run<T>(_ operation: () async throws -> T,
defer deferredOperation: () async throws -> Void) async throws -> T {
do {
let result = try await operation()
try await deferredOperation()
return result
} catch {
try await deferredOperation()
throw error
}
}
// Usage:
try await run {
print("doing")
try await Task.sleep(for: .seconds(1))
print("done")
} defer: {
try await Task.sleep(for: .milliseconds(100))
print("cleanup done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment