Last active
August 5, 2024 01:34
-
-
Save finestructure/500d9fda7dfc99400e8ef5bddb38776b to your computer and use it in GitHub Desktop.
Async defer
This file contains 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
@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