PromiseK 为 Swift 提供了一个简单的单子 (monadic) Promise
类型。
// `flatMap` is equivalent to `then` of JavaScript's `Promise`
let a: Promise<Int> = asyncGet(2)
let b: Promise<Int> = asyncGet(3).map { $0 * $0 } // Promise(9)
let sum: Promise<Int> = a.flatMap { a in b.map { b in a + b } }
Promise
可以与 throws
协同工作,用于处理可能失败的异步操作。
// Collaborates with `throws` for error handling
let a: Promise<() throws -> Int> = asyncFailable(2)
let b: Promise<() throws -> Int> = asyncFailable(3).map { try $0() * $0() }
let sum: Promise<() throws -> Int> = a.flatMap { a in b.map { b in try a() * b() } }
也可以从错误中恢复。
// Recovery from errors
let recovered: Promise<Int> = asyncFailable(42).map { value in
do {
return try value()
} catch _ {
return -1
}
}
.package(
url: "https://github.com/koher/PromiseK.git",
from: "3.0.0"
)
github "koher/PromiseK" ~> 3.0.0