Search code examples
iosswiftpromisekit

Using same then/catch/finally blocks for two promises of different types


I have the following operations:

class CreateObjectOperation {
    // ...

    func promise() -> Promise<Object>
}

class DeleteObjectOperation {
    // ...

    func promise() -> Promise<Void>
}

I want to be able to use the same then/catch/finally blocks for both. I tried the following:

let foo: Bool = ...
firstly {
    (foo ?
        CreateObjectOperation().promise() :
        DeleteObjectOperation().promise()
    ) as Promise<AnyObject>
}.then { _ -> Void in
    // ...
}.finally {
    // ...
}.catch { error in
    // ...
}

but this does not compile. Is there any working solution (apart from moving the code from blocks to separate functions, which I would like to avoid)?


Solution

  • Found it:

    firstly { _ -> Promise<Void>
        (foo ?
            CreateObjectOperation().promise().then { _ in Promise<Void>() } :
            DeleteObjectOperation().promise()
        ) as Promise<AnyObject>
    }.then { _ -> Void in
        // ...
    }