Writing Cleaner Asynchronous Objective-C/Swift Code with PromiseKit

Tags: objective-c ios swift

PromiseKitis a library that adds    Promisessupport to Objective-C and Swift.    Promises (sometimes referred to as “Futures”)can help clean up some of the spaghetti-callback-ridden code that we’ve all written then never talked about again.

The main thing you should take away from this bite is that    PromiseKitlets you turn repulsive, close to gibberesh code like this:

SynapseAPI.loadVideos { (videos, error) in
 if let e = error { showError(e) } else {
   var completed = 0
   var total = videos.length

   for video in videos {
     PiedPiperAPI.loadVideo { loadedVideo in
       if completed == total {
         // finally done, UGH SRSLY


…into much more readable, and composable:

firstly {
}.then { videos in
 // `join` waits for all the requests to finish, then continues
 join(videos.map { PiedPiperAPI.loadVideo($0) })
}.catch { error in
 // called if any error happens anywhere in the chain
}.finally {
 // done, much nicer


The power of Promises doesn’t stop at network calls!    PromiseKitcomes with extensions Promise-ifying many of the traditionally disperate parts of Cocoa and Cocoa Touch like    CLLocationManager,    UIAlertView, and even sending a user off to another    UIViewController, letting them choose something, then continuing on.

More info about    PromiseKitcan be found at    git.io/promisekit