Search code examples
swiftpromisekit

How to use a method with throws returning a value in promiseKit


I create a set of promises which relies on the results from a function that may throw an error. I can get this to work as shown in the code below, but I don't like the double catch blocks. I'd like to use the a single promiseKit catch block. Anyone have a better solution that works?

do {
    let accounts = try Account.getAccounts()
    let mailboxPromises = accounts.map { self.fetchMailboxes($0) }

    when(fulfilled: mailboxPromises).map { _ in
        self.updateBadgeCount()
    }
    .catch { (error) in

    }
} catch  {

}

Solution

  • Maybe wrap Account.getAccounts() in a promise which you can then use in your promise chain?

    func getAccounts() -> Promise<[Account]> {
        return Promise {
            do {
                let accounts = try Account.getAccounts()
                $0.fulfill(accounts)
            } catch {
                $0.reject(error)
            }
        }
    }
    

    UPDATE:

    Below info is from the documentation at https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md so you should be able to use this pattern instead of your do/catch block.

    Since promises handle thrown errors, you don't have to wrap calls to throwing functions in a do block unless you really want to handle the errors locally:

    foo().then { baz in
        bar(baz)
    }.then { result in
        try doOtherThing()
    }.catch { error in
        // if doOtherThing() throws, we end up here
    }