Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a Promise from a completion handler in PromiseKit

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!

like image 778
7ball Avatar asked Dec 17 '25 06:12

7ball


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)
       })
   }
}
like image 97
Trevor Avatar answered Dec 19 '25 21:12

Trevor


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)
        })
    }
}
like image 40
Daniel T. Avatar answered Dec 19 '25 22:12

Daniel T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!