ShallowPromises

License codebeat badge

Swift 5 的 Promise 库。

这是一个提供基本 Promise 功能的简单库。

特性

注意事项

安装

创建 Promises

通常,Promise 提供者 在确定的 队列 中创建 Promise,并立即将其返回给 接收者

func requestUser() -> Promise<User> {
    let promise = Promise<User>()
    networkingQueue.async {
        // make HTTP request to get the user
    }
    return promise
}

实现 Promises

将来某个时候,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接收者 将必要的闭包添加到其中,可以添加到 Promise 的闭包有四种:then onSuccess onErrorfinally

requestUser()
    .then(requestFavorites(of:))
    .onSuccess(updateFavorites)
    .onError(logError)
    .finally(updateView)

可以向每个 Promise 添加多个闭包。

链式 Promises

可以使用 then 链接 promise,此方法接受一个闭包或函数,该闭包或函数将在先前的 promise 完成后使用其结果调用,并返回一个新的 promise

 requestInt(from: "1")
    .then(requestString(from:))
    .then(requestInt(from:))
    .then(requestString(from:))
    .onSuccess { result in
    print(result)
 }

闭包和 队列

调用 thenonSuccessonErrorfinally 闭包的 队列 由以下规则决定

  1. 如果闭包注册了特定的队列,则闭包将在该队列中调用
requestInt(from: "1").onSuccess(in: .main) { result in
    print("in main queue: \(result)")
}

如果未指定队列

requestInt(from: "1").onSuccess { result in
    print("\(result)")
}

那么

  1. 如果 Promise 提供者 在实现 promise 时指定了闭包,则闭包将在该队列中调用
promise.fulfill(with: result, in: .global())

如果未指定队列

promise.fulfill(with: result)

那么

  1. 闭包在调用 fulfill 方法的当前队列中调用。

取消 Promises

接收者 可以通过调用 Promise 的 cancel 方法来取消 Promise,在这种情况下,将使用 PromiseFailure.cancelled 错误调用 onError 闭包

let promise = requestUser().onError(logError)
promise.cancel()