被放弃的承诺会怎样?

What happens to a promise that's abandoned?

我在视图控制器中定义了以下代码。

    _ = accountService.getAccount()

      .then { user -> Void in

         self.txtBxUser.text = user.username
         self.txtBxEmail.text = user.email
   }

getAccount 发出 REST API 请求。

如果用户在调用返回之前关闭视图控制器,回调链会发生什么情况?它仍然 运行 鉴于我认为它仍然被引用吗?

Should I be concerned about retain cycles? tl;dr: it’s safe to use self in promise handlers.

This is safe:

somePromise.then {
    self.doSomething()
}

Provided somePromise resolves, the function passed to then will be released, thus specifying [weak self] is not necessary.

Specifying [unowned self] is likely dangerous.

You’re telling me not to worry about retain cycles?! No, it’s just that by default you are not going to cause retain cycles when using PromiseKit. But it is still possible, for example:

self.handler = {
    self.doSomething
    self.doSomethingElse }
somePromise.then(execute: self.handler)

The closure we assign to handler strongly retains self. handler is strongly retained by self. It’s a typical retain cycle. Don’t write typical retain cycles!

Notably, this is not a retain cycle:

 somePromise.then(execute: self.doSomething).then(execute: self.doSomethingElse)

source

If the user dismisses the view controller before the call has returned, what happens to the call back chain? Does it still run given that, I presume, it's still referenced?

是的,它仍然 运行。

请注意,闭包中对 self 的引用意味着它还保留对视图控制器的引用,直到 then 闭包完成 运行ning。出于这个原因,如果视图控制器有可能被关闭,您可能需要使用 weak 参考:

_ = accountService.getAccount().then { [weak self] user -> Void in
    self?.txtBxUser.text = user.username
    self?.txtBxEmail.text = user.email
}

理想情况下,您还应该使 getAccount 可取消并在视图控制器的 deinit 中取消它。

(注意,在 FAQ - Should I be Concerned About Retain Cycles 中,PromiseKit 文档指出您不需要 weak 引用,这是正确的。这只是您是否介意重新分配的问题被取消的视图控制器被推迟到承诺实现之后。)