Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PromiseKit with Swift: terminate chain of promises

I'm trying to use PromiseKit with Swift. I am not really familiar with it, and there doesn't seem to be much information on its usage with Swift.

I can't seem to figure out how to terminate a chain of promises. As long as the last (terminal) then block contains a single statement, everything is fine:

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

However, if I try to add another statement, compiler complains:

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

Obviously, the solution is to return another promise, but it doesn't make sense in the terminal block. Is there anything else I can do?

like image 666
Andrii Chernenko Avatar asked Jun 19 '15 13:06

Andrii Chernenko


People also ask

How do I cancel a promise in Swift?

The promise can then be cancelled by calling cancellablePromise. cancel() from the outside. The lib also overloads when and race to cancel tasks automatically. Save this answer.

What is Promise Swift?

Promises is a modern framework that provides a synchronization construct for Objective-C and Swift to facilitate writing asynchronous code.


2 Answers

According to http://promisekit.org/PromiseKit-2.0-Released/, under Swift Compiler Issues section:

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

So you'll have to change your code to:

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

Or you can use obj -> Void to stop the chain

like image 178
Soheil Jadidian Avatar answered Oct 21 '22 10:10

Soheil Jadidian


Change it to:

firstly {
    // ...
}.then { obj -> Void in
    self.handleResult(obj)
    self.doSomethingDifferent(obj)
}.catch { error in
    self.handleError(error)
}
like image 26
João Nunes Avatar answered Oct 21 '22 08:10

João Nunes