How to sync 2 asynchronous fetch in Parse?

So I have a PFobject A that contains 2 other PFobjects BC as a value. When I create my local object a, I need both B C objects. So first I retrieve a by doing the query:

let query = PFQuery(className: "A")
query.getObjectInBackgroundWithId("1", block: { (a, error) -> Void in


Then I get b and c from a

var b = a!["B"] as! PFObject
var c = a!["C"] as! PFObject


Then I will need to get objects b and c individually

b.fetchInBackgroundWithBlock({ (fetchedB, error) -> Void in


The problem is that the fetch methods are asynchronous, and if I put them on the same thread, I cannot guarantee that both of them will be fetched at the end.

One solution is for the selection to be nested within the callbacks so that as soon as one selection is done, it will trigger another.

b.fetchInBackgroundWithBlock({ (fetchedB, error) -> Void in
    c.fetchInBackgroundWithBlock({ (fetchedC, error) -> Void in
        println(fetchedC) // Now they have values
        var myA = A(validB: fetchedB, validC: fetchedC) // Construction can continue


But if more objects are required, it will be nested in the nest. How:

b.fetchInBackgroundWithBlock({ (fetchedB, error) -> Void in
    c.fetchInBackgroundWithBlock({ (fetchedC, error) -> Void in
        d.fetchInBackgroundWithBlock({ (fetchedD, error) -> Void in
            e.fetchInBackgroundWithBlock({ (fetchedE, error) -> Void in


However, b, c, d and e are independent of each other - it must be perfect to retrieve them on separate threads!

So, is there a way to make the callbacks wait for each other at some point on the main thread to make sure all objects are fetched?



source to share

1 answer

Use the method includeKey()

in the first PFQuery

to tell the parsing to extract both class B and C when you execute a query. Relevant documentation forincludeKey



All Articles