使用Swift的PromiseKit:终止承诺链

前端之家收集整理的这篇文章主要介绍了使用Swift的PromiseKit:终止承诺链前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将PromiseKit与 Swift一起使用.我对它并不熟悉,并且似乎没有太多关于它与Swift一起使用的信息.

我似乎无法弄清楚如何终止承诺链.只要最后一个(终端)块然后包含一个语句,一切都很好:

firstly {
    // ...
}.then { obj in
    self.handleResult(obj)
}.catch { error in
    self.handleError(error)
}

但是,如果我尝试添加另一个语句,编译器会抱怨:

firstly {
    // ...
}.then { obj in
    self.handleResult(obj)
    self.doSomethingDifferent(obj)
}.catch { error in // compiler error: Missing return in a closure expected to return 'AnyPromise'
    self.handleError(error)
}

显然,解决方案是返回另一个承诺,但它在终端块中没有意义.还有什么我可以做的吗?

根据 http://promisekit.org/PromiseKit-2.0-Released/,在Swift Compiler Issues部分下:

The Swift compiler will often error with then. To figure out the
issue,first try specifying the full signature for your closures:

foo.then { x in
    doh()
    return bar()
}

// will need to be written as:

foo.then { obj -> Promise<Type> in
    doh()
    return bar()
}

// Because the Swift compiler cannot infer closure types very
// well yet. We hope this will be fixed.

// Watch out for  one-line closures though! Swift will
// automatically infer the types,which may confuse you:

foo.then {
    return bar()
}

因此,您必须将代码更改为:

firstly {
    // ...
}.then { obj -> Promise<WhateverTypeDoSomethingDifferentPromises> in
    self.handleResult(obj)
    self.doSomethingDifferent(obj)
}.catch { error in
    self.handleError(error)
}

或者你可以使用obj – >无效阻止链条

原文链接:https://www.f2er.com/swift/319542.html

猜你在找的Swift相关文章