Skip to content

Instantly share code, notes, and snippets.

@ChristianKienle
Last active May 18, 2018 09:10
Show Gist options
  • Save ChristianKienle/dfacabcf3b8c27e4640575422d6df907 to your computer and use it in GitHub Desktop.
Save ChristianKienle/dfacabcf3b8c27e4640575422d6df907 to your computer and use it in GitHub Desktop.
simplest Promise framework possible?
public struct Promise<T> {
typealias Fulfiller = (T) -> (Void)
typealias Rejecter = (Void) -> (Void)
typealias Resolver = (_ fulfill: @escaping Fulfiller, _ reject: @escaping Rejecter) -> (Void)
let resolver: Resolver
init(_ resolver: @escaping Resolver){
self.resolver = resolver
}
func then<U>(_ execute: @escaping ((T) -> U)) -> Promise<U> {
return Promise<U>({(fulfill, reject) in
let onSuccess: ((T) -> (Void)) = { value in
fulfill(execute(value)); return
}
let onError: ((Void) -> (Void)) = { print("error") }
self.resolver(onSuccess, onError)
})
}
}
// USAGE: First load google.de then spiegel.de then amazon.de
let session = URLSession.shared
session.get("http://google.de").then { response in
return session.get("http://spiegel.de")
}.then { response in
return session.get("http://amazon.de")
}.then { response in
// do nothing
}
// Custom Promises
extension URLSession {
func get(_ urlString: String) -> Promise<URLResponse> {
return Promise({ (fulfill, reject) in
guard let url = URL(string: urlString) else {
reject()
return
}
self.dataTask(with: url) { (body, response, error) in
guard let response = response else {
reject()
return
}
fulfill(response)
}.resume()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment