Package - koher/PromiseK

PromiseK

PromiseK provides the Promise class designed as a Monad for Swift.

// `flatMap` is equivalent to `then` of JavaScript's `Promise`
let a: Promise<Int> = asyncGet(2).flatMap { asyncGet($0) }.flatMap { asyncGet($0) }
let b: Promise<Int> = asyncGet(3).map { $0 * $0 }
let sum: Promise<Int> = a.flatMap { a0 in b.flatMap { b0 in Promise(a0 + b0) } }

// uses `Optional` for error handling
let mightFail: Promise<Int?> = asyncFailable(5).flatMap { Promise($0.map { $0 * $0 }) }
let howToCatch: Promise<Int> = asyncFailable(7).flatMap { Promise($0 ?? 0) }

// `>>-` operator is equivalent to `>>=` in Haskell
// can use `>>-` instead of `flatMap`
let a2: Promise<Int> = asyncGet(2) >>- { asyncGet($0) } >>- { asyncGet($0) }
// a failable operation chain with `>>-`
let failableChain: Promise<Int?> = asyncFailable(11) >>- { $0.map { asyncFailable($0) } }
// also `>>-?` operator is available
let failableChain2: Promise<Int?> = asyncFailable(11) >>-? { asyncFailable($0) }

Installation

Carthage

Carthage compatible

Carthage is available to install PromiseK. Add it to your Cartfile:

github "koher/PromiseK" ~> 2.0

Manually

Embedded Framework

For iOS 8 or later,

  1. Put PromiseK.xcodeproj into your project in Xcode.
  2. Click the project icon and select the "General" tab.
  3. Add PromiseK.framework to "Embedded Binaries".
  4. import PromiseK in your swift files.

Source

For iOS 7, put all swift files in the Source directory into your project.

License

The MIT License

References

  1. Promise - JavaScript | MDN
  2. JavaScript Promises: There and back again - HTML5 Rocks
  3. A Fistful of Monads - Learn You a Haskell for Great Good!

Github

link
Stars: 28

Advertisement

Releases

3.0.0-alpha.4 - Oct 18, 2017

Now multiple fulfill calls cause a logic failure.

3.0.0-alpha.3 - Oct 18, 2017

- init(_ executor: (_ resolve: @escaping (Promise<Value>) -> ()) -> ())
+ init(_ executor: (_ fulfill: @escaping (Value) -> ()) -> ()) {

3.0.0-alpha.2 - Oct 18, 2017

3.0.0-alpha - May 2, 2017

2.4.0 - May 2, 2017