0

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  {

}
Steig
  • 173
  • 2
  • 5

1 Answers1

1

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
}
rodskagg
  • 3,827
  • 4
  • 27
  • 46
  • using a try in a then or done works, but it doesn't work in a firstly which is where I need to use it. The first solution you suggest is the only one that seems to work, but it really doesn't result in a less complex solution. – Steig Apr 19 '19 at 09:48