2

I have a Promise<T> that I would like to transform into a Guarantee<Bool> where true means the promise fulfilled and false if it got rejected.

I managed to reach this using

  return getPromise()
    .map { _ in true }
    .recover { _ in Guarantee.value(false) }

I'm wondering if there is a neater way to do this.

Raphael Oliveira
  • 7,751
  • 5
  • 47
  • 55

2 Answers2

1

Expanding on the original code and the answers here, I would make the extension explicitly for Void Promises, and keep the naming more inline with PromiseKit:

extension Promise where T == Void {
    func asGuarantee() -> Guarantee<Bool> {
        self.map { true }.recover { _ in .value(false) }
    }
}
jowie
  • 8,028
  • 8
  • 55
  • 94
0

You can extend promise as below for easy usage mentioned under Usage

extension Promise {

    func guarantee() -> Guarantee<Bool> {
        return Guarantee<Bool>(resolver: { [weak self] (body) in
            self?.done({ (result) in
                body(true)
            }).catch({ (error) in
                body(false)
            })
        })
    }
}

Usage:

// If you want to execute a single promise and care about success only.
getPromise().guarantee().done { response in
    // Promise success handling here.
}

// For chaining multiple promises
getPromise().guarantee().then { bool -> Promise<Int> in
        return .value(20)
    }.then { integer -> Promise<String> in
        return .value("Kamran")
    }.done { name in
        print(name)
    }.catch { e in
        print(e)
}
Kamran
  • 14,987
  • 4
  • 33
  • 51