An Chin
An Chin

Reputation: 463

How to sync 2 async fetches in Parse?

So I have a PFobject A that contains 2 other PFobjects B C as value. When I construct my local object a, I would need both of the objects B C. So first I fetch a by doing a 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 fetch b and c objects individually

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

The problem is, the fetching methods is async and if I put them in the same thread I won't be guaranteed to have both of them fetched in the end.

One solution is to have the fetching nested in call-backs so that once one fetch is done it will start the other.

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

But if more objects are needed, it will become nesting in nesting. Like:

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 not dependent on each other - it should be perfect to fetch them on separate threads!

So is there a way to make the call-backs wait for each other at some point in the main thread to make sure all objects are fetched?

Thanks!

Upvotes: 4

Views: 116

Answers (1)

hhanesand
hhanesand

Reputation: 1000

Use the includeKey() method on the first PFQuery to tell parse to fetch both class B and C when performing the query. Relevant documentation for includeKey

Upvotes: 1

Related Questions