Last active
May 18, 2018 09:10
-
-
Save neilco/9744b2e0f6429ba7bfc6 to your computer and use it in GitHub Desktop.
Coffee Break Hack - Ultra-simple Promises
This file contains hidden or 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 final class Promise<T> { | |
private var resolveClosure: (T -> Void)? | |
private var rejectClosure: (AnyObject? -> Void)? | |
public init() { } | |
public func then(resolve: (T -> Void), _ reject: (AnyObject? -> Void)? = nil) -> Promise<T> { | |
self.rejectClosure = reject | |
self.resolveClosure = resolve | |
return self | |
} | |
public func resolve(a: T) { | |
if let reject = self.resolveClosure { | |
reject(a) | |
} | |
} | |
public func reject(error: AnyObject?) { | |
if let reject = self.rejectClosure { | |
reject(error) | |
} | |
} | |
} |
This file contains hidden or 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
// | |
// This creates an async task that returns a Promise. | |
// | |
import Foundation | |
typealias ResponseTuple = (NSHTTPURLResponse, NSData) | |
func longRunningTask() -> Promise<ResponseTuple> { | |
var p = Promise<ResponseTuple>() | |
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { | |
let session = NSURLSession.sharedSession() | |
let task = session.dataTaskWithURL(NSURL(string: "http://date.jsontest.com")!, completionHandler: { (data, response, error) -> Void in | |
if error != nil { | |
p.reject(error) | |
} | |
else { | |
p.resolve((response as NSHTTPURLResponse, data)) | |
} | |
return | |
}) | |
task.resume() | |
}) | |
return p | |
} |
This file contains hidden or 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
// | |
// This shows how to define the resolve and reject closures for the Promise | |
// | |
import Foundation | |
NSLog("Calling") | |
longRunningTask().then({ (result: (NSHTTPURLResponse, NSData)) in // resolved | |
NSLog("Resolved: %@", NSString(data: result.1, encoding: NSUTF8StringEncoding)!) | |
NSLog("Response: %@", result.0) | |
}, { error in // rejected | |
NSLog("Rejected: %@", error as NSObject) | |
}) | |
NSLog("Waiting") | |
NSRunLoop.currentRunLoop().runUntilDate(NSDate().dateByAddingTimeInterval(5)!) | |
NSLog("Exiting") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment