【问题标题】:PromiseKit cancel a promisePromiseKit 取消承诺
【发布时间】:2017-10-09 23:06:59
【问题描述】:

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

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)
}

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

【问题讨论】:

  • Promisekit github 页面上有一个关于 Promise 链取消的线程。你检查here了吗?
  • 我明白了,谢谢@ridvankucuk。我可以看到它并不像我最初想象的那么微不足道。
  • 您最好研究一下 RxSwift、ReactiveKit、Interstellar 或其他响应式 SDK 之一来完成此类工作。
  • 再次感谢您的建议。其中,你有最喜欢的吗?

标签: ios swift promisekit


【解决方案1】:

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

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

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

更新:

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

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

【讨论】:

    【解决方案2】:

    也许我的库 CancellablePromiseKit 对你有用:https://github.com/johannesd/CancellablePromiseKit

    它允许您像定义普通 Promise 一样定义 CancellablePromise,但添加了一个取消块。在该块中,您编写用于取消基础任务的代码。然后可以通过从外部调用cancellablePromise.cancel() 来取消承诺。

    let cancellablePromise = CancellablePromise<String> { resolver in
        let currentOperation = client.load(skip: skip, query: nil)
        currentOperation.completion = { (value, error) in
            resolver.resolve(value, error)
        }
        return {
            // The cancel block
            currentOperation.stop()
        }
    }
    

    lib 还会重载 when 和 race 以自动取消任务。

    【讨论】:

      【解决方案3】:

      在 PromiseKit 7 中,使用 func cancellize()PromiseGuarantee 转换为可以取消的承诺:

      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)
      }
      

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

      currentOperationCancellable.cancel()
      currentOperationCancellable.cancel(with: NSError(domain: "", code: 0, userInfo: nil))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-06
        • 1970-01-01
        • 2015-12-14
        • 1970-01-01
        • 2015-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多