Skip to content

Instantly share code, notes, and snippets.

@neilco
Last active May 18, 2018 09:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neilco/9744b2e0f6429ba7bfc6 to your computer and use it in GitHub Desktop.
Save neilco/9744b2e0f6429ba7bfc6 to your computer and use it in GitHub Desktop.
Coffee Break Hack - Ultra-simple Promises
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 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 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