Search code examples
swiftpromisekit

How to set up when(fulfilled:) in PromiseKit?


I have a function set up to return a Promise<PFObject>. I would like to use this function in PromiseKit's when(fulfilled:) functionality, but whenever I try to do so, I get an error. Here is the function which returns the Promise<PFObject>:

func Query() -> Promise<PFObject>{
        return Promise{ fulfill, reject in
            let linkQueryy = PFUser.query()
            linkQueryy?.findObjectsInBackground(block: { (objectss, error) in
                if let objects = objectss{
                    for object in objects{
                        fulfill(object)
                    }
                }
            })
        }
    }

As you can see, the function returns the Promise upon fulfillment. Thus, I tried to set up a when statement in my viewDidLoad() as follows:

override func viewDidLoad() {
        super.viewDidLoad()

        when(fulfilled: Query()).then{
            //do more asynch stuff
        }
    }

However, I get the error that xcode cannot "invoke 'when' with an argument list type of '(fulfilled: Promise<PFObject>)'". I do not know how to fix this as I thought I had it set up correctly. The when needs a promise, and I am giving it one so I am not sure what to do.


Solution

  • Try as follows :

    when(fulfilled: [linkQueryy()] as! [Promise<Any>]).then { _ in
        // do more asynch stuff
    }
    

    The parameter fulfilled: needs to be an iterable.

    By the way, when(fulfilled:) is necessary only when you have many promises and need wait for all to complete successfully. But in your code, you need to wait for only one promise.

    For a single promise, the better way is to form a chain as follows :

    firstly {
        linkQueryy()
    }.then { _ -> Void in
        // do more asynch stuff
    }.catch { _ in
        // error!
    }