PromiseKit取消承诺

Jas*_*ues 5 ios swift promisekit

如何取消尚未履行或拒绝的承诺?

PromiseKit的文档讨论了取消承诺,但我找不到如何执行此操作的具体示例.

鉴于:

currentOperation = client.load(skip: skip, query: nil)
currentOperation!.then { (items) in
   self.processItems(items: items, skip: skip, query: query)
}.catch { (error) in
    print("failed to load items - just retrying")
    self.loadIfNeeded(skip: skip, query: query, onlyInStock: onlyInStock)
}
Run Code Online (Sandbox Code Playgroud)

如果查询更改(用户在搜索栏中输入了一些文本),我想取消并放弃currentOperation,开始新的承诺.

小智 5

为了取消一个承诺,你必须用任何符合CancellableError协议的错误类型来拒绝它。这样,任何policy参数设置为 的catch 块allErrorsExceptCancellation都会让错误通过。

如果你需要一个 CancelablePromise ,你可以继承 Promise 并实现一个 cancel() 函数,该函数将拒绝一个CancellableErrorwhen 调用。这是一个最小的实现:

https://gist.github.com/EfraimB/918eebdf7dd020801c72da1289c8d797

更新:

这是新 PromiseKit 版本 (6.4.1) 的更新

https://gist.github.com/EfraimB/3ac240fc6e65aa8835df073f68fe32d9


Rom*_*mov 1

在 PromiseKit 7 中,使用func cancellize()Promiseor转换Guarantee为可以取消的 Promise:

currentOperation = client.load(skip: skip, query: nil)
let currentOperationCancellable = currentOperation!.then { (items) in
   self.processItems(items: items, skip: skip, query: query)
}.cancellize()
currentOperationCancellable.catch { (error) in
    print("failed to load items - just retrying")
    self.loadIfNeeded(skip: skip, query: query, onlyInStock: onlyInStock)
}
Run Code Online (Sandbox Code Playgroud)

使用func cancel()func cancel(with:)取消可取消的PromiseGuarantee

currentOperationCancellable.cancel()
currentOperationCancellable.cancel(with: NSError(domain: "", code: 0, userInfo: nil))
Run Code Online (Sandbox Code Playgroud)