Last active
June 17, 2021 21:10
-
-
Save rommex/5c6a14114209e1072e9524b1d29c396e to your computer and use it in GitHub Desktop.
Example with Promises
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
private func fetchData() -> Promise<[Int]> { | |
return Promise { seal in | |
let someData = (1...100_000).map { _ in Int.random(in: (1...100)) } | |
seal.fulfill(someData) | |
} | |
} | |
private func calculateMinMax(forData array: [Int]) -> Promise<(Int, Int)> { | |
return Promise { seal in | |
guard let first = array.first else { | |
seal.reject(DataError.emptyArray) | |
return | |
} | |
var min = first | |
var max = first | |
for item in array.dropFirst() { | |
if min > item { | |
min = item | |
} | |
if max < item { | |
max = item | |
} | |
} | |
seal.fulfill((min, max)) | |
} | |
} | |
private func updateUI(with data: (Int, Int)) -> Promise<Void> { | |
return Promise { seal in | |
self.textLabel.text = "min is \(data.0), max is \(data.1)" | |
seal.fulfill(()) | |
} | |
} | |
private func doJob() { | |
fetchData() | |
.then { array in self.calculateMinMax(forData: array) } | |
.then (on: .main) { (min, max) in | |
self.updateUI(with: (min, max)) | |
}.catch { error in | |
print(error.localizedDescription) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment