Swift 5 的 Promise 库。
这是一个提供基本 Promise 功能的简单库。
通常,Promise 提供者 在确定的 队列 中创建 Promise,并立即将其返回给 接收者
func requestUser() -> Promise<User> {
let promise = Promise<User>()
networkingQueue.async {
// make HTTP request to get the user
}
return promise
}
将来某个时候,Promise 提供者 在确定的 队列 中实现 promise,接收者 使用结果。
do {
let result = try JSONDecoder().decode(User.self, from: data)
promise.fulfill(with: result, in: responseQueue)
} catch {
promise.complete(with: error, in: responseQueue)
}
Promise 的接收者 将必要的闭包添加到其中,可以添加到 Promise 的闭包有四种:then onSuccess onError 和 finally
requestUser()
.then(requestFavorites(of:))
.onSuccess(updateFavorites)
.onError(logError)
.finally(updateView)
可以向每个 Promise 添加多个闭包。
可以使用 then 链接 promise,此方法接受一个闭包或函数,该闭包或函数将在先前的 promise 完成后使用其结果调用,并返回一个新的 promise
requestInt(from: "1")
.then(requestString(from:))
.then(requestInt(from:))
.then(requestString(from:))
.onSuccess { result in
print(result)
}
调用 then、onSuccess、onError 或 finally 闭包的 队列 由以下规则决定
requestInt(from: "1").onSuccess(in: .main) { result in
print("in main queue: \(result)")
}
如果未指定队列
requestInt(from: "1").onSuccess { result in
print("\(result)")
}
那么
promise.fulfill(with: result, in: .global())
如果未指定队列
promise.fulfill(with: result)
那么
fulfill 方法的当前队列中调用。接收者 可以通过调用 Promise 的 cancel 方法来取消 Promise,在这种情况下,将使用 PromiseFailure.cancelled 错误调用 onError 闭包
let promise = requestUser().onError(logError)
promise.cancel()