Skip to content

Instantly share code, notes, and snippets.

@rommex
Last active June 17, 2021 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rommex/5c6a14114209e1072e9524b1d29c396e to your computer and use it in GitHub Desktop.
Save rommex/5c6a14114209e1072e9524b1d29c396e to your computer and use it in GitHub Desktop.
Example with Promises
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