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
       completed++
       if completed == total {
         // finally done, UGH SRSLY
       }
     }
   }
 }
}

 

…into much more readable, and composable:

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!    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   

本文链接:http://www.4byte.cn/learning/119771/writing-cleaner-asynchronous-objective-c-swift-code-with-promisekit.html