Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The Young Rappel

The Young Rappel

Futures and Promises on Swift

Sergio Fernández

July 05, 2017
Tweet

More Decks by Sergio Fernández

Other Decks in Programming

Transcript

  1. Request Image login(with: credentials) { (result: JSONResponse) in if case

    .success(let json) = result, let user = User(with: json) { fetch(avatar: user.avatarURL) { (result: DataResponse) in if case .success(let data) = result { let image = UIImage(data: data) self.imageView = UIImageView(image: image) } } } }
  2. Request Image login(with: credentials) .then(User.init) .then { user in return

    fetch(avatar: user.avatarURL) }.then { data in self.imageView.image = UIImage(data: data) }.catch { error in // handle error } }
  3. Futures & Promises It is the way to handle complex

    asynchronous operations in a simple way
  4. A promise is an object that may produce a single

    value some time in the future
  5. Promise func login(with credentials: Credentials) -> Promise<User> { return Promise

    { fulfill, reject in self.client.request(task: .login(credentials)) { result in switch result { case .success(let json): fulfill(User(with: json)) case .failure(let error): reject(error) } } } }
  6. Limitations of Futures → Promises can only produce one value

    → Can nwot encapsulate streams of values → Only consumer driven
  7. Back to the Future → Abstraction for async/sync operations →

    Encapsulate a deferred computation → Centralized error handling → Easily composable