Created
April 28, 2020 10:14
-
-
Save TerryCK/0238a2a35b580b0a16c9e3cbb948e8ea to your computer and use it in GitHub Desktop.
practice of await/async
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
struct Promise<T, Error: Swift.Error> { | |
let handler: (Result<T, Error>) -> Void | |
} | |
extension Promise where T == Payload { | |
func fire() -> Result<T, Error> { | |
var result: Result<T, Error>! | |
let semaphore = DispatchSemaphore(value: 0) | |
DispatchQueue.global().async { | |
defer { semaphore.signal() } | |
sleep(10) | |
result = Result.success(Payload(name: "Terry")) | |
self.handler(result) | |
} | |
semaphore.wait(timeout: .distantFuture) | |
let payload = try! result.get() | |
print(payload, result!, Date()) | |
// sleep(5) | |
return result | |
} | |
} | |
struct Payload { | |
let name: String | |
} | |
let promise = Promise<Payload, Never> { (result) in | |
print(result, Date()) | |
} | |
print("before call await function", Date()) | |
let result = promise.fire() | |
print(result, Date()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment