Topics

#13: PromiseKit 💍

Topics

PromiseKit is a library that adds Promises support 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 PromiseKit lets 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
        completed++
        if completed == total {
          // finally done, UGH SRSLY
        }
      }
    }
  }
}

...into much more readable, and composable code like this:

firstly {
  SynapseAPI.loadVideos()
}.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! PromiseKit comes 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 PromiseKit can be found at git.io/promisekit