Returning a Promise from a completion handler in PromiseKit

Viewed 1588

I have the following problem:

func doSomething() -> Promise<Bool> {

  let completionHandler = { (result: Bool) in
    // How can I fulfill the promise here -- Promise { fulfill, _ in fulfill(result) } 
  }

  someLibrary.doSomeTasks(handler: completionHandler)
  // What do I return for this function?...
}

Currently I don't know what to return / how to return a Promise<Bool> because the bool value isn't available until the completion handler is finished. someLibrary.doSomeTasks doesn't support PromiseKit so I'm stuck with using the completion handler like shown. Thanks!

2 Answers

this has been updated in promiseKit 6 to:

func doSomething() -> Promise<Bool> {
   return Promise<Bool> { seal in 
       someLibrary.doSomeTask(handler: { value in
           seal.fullfill(value)

           // we also have seal.reject(error), seal.resolve(value, error)
       })
   }
}

Here is the general form to do what you want:

func doSomething() -> Promise<Bool> {
    return Promise { fulfill, reject in 
        someLibrary.doSomeTask(handler: { value in
            fulfill(value)
        })
    }
}
Related