Last active
May 18, 2018 09:10
-
-
Save ChristianKienle/dfacabcf3b8c27e4640575422d6df907 to your computer and use it in GitHub Desktop.
simplest Promise framework possible?
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
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) | |
}) | |
} | |
} |
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
// 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 | |
} |
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
// 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