Skip to content

Instantly share code, notes, and snippets.

@rhlsthrm
Last active January 31, 2019 03:20
Show Gist options
  • Save rhlsthrm/8362b59f0bd22b36f78658880b047057 to your computer and use it in GitHub Desktop.
Save rhlsthrm/8362b59f0bd22b36f78658880b047057 to your computer and use it in GitHub Desktop.
Using PromiseKit and AwaitKit to write synchronous looking async code.
import PromiseKit
import AwaitKit
struct Todo: Decodable {
var userId: Int
var id: Int
var title: String
var completed: Bool
}
function loadTodos() -> Promise<[Todo]> {
return async {
// get promises for each HTTP request
let requestPromises = Array(0...10).compactMap { (todo) -> Promise<(data: Data, response: URLResponse)>? in
let urlString = "https://jsonplaceholder.typicode.com/todos/\(todo)"
guard let url = URL(string: urlString) else { return }
return URLSession.shared.dataTask(.promise, with: url).validate()
}
// wait for all the promises to complete and iterate through the responses
let results = try await(when(fulfilled: requestPromises))
// decode the JSON from the responses as Todo objects
return results.map { try JSONDecoder().decode(Todo.self, from: $0.data) }
}
}
function printTodos() {
firstly {
loadTodos()
}.done { todos in
todos.forEach { print($0) }
}.catch { error in
print("Handle me!!")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment