1

I'm using Parse Cloud Code to host a web application but I'm having a problem trying to get a relation query to work. I've tried an example from Coderwall https://coderwall.com/p/n22mqq/including-relational-data-in-a-query-parse-com but I'm not sure how to gather the result of the query before trying to render the result.

function queryProducts(limit) {

  var post = Parse.Object.extend("Post");
  var query = new Parse.Query(post);
  query.limit(limit);

  var data = new Array();

  query.find().then(function (posts) {
    var cb = _.after(posts.length, function () {
      console.log("after"+ data);
      return data;
    });
    _.each(posts, function (post) {
      var images = post.relation("images");
      images.query().find().then(function (images) {
        data.push(post);
        cb();
      });
    });
  });
}

app.get('/', function (req, res) {
  results = queryProducts(10);
  res.render('index', { products: results });
});
2
  • queryProducts is asynchronous. You should get more familiar with promises Commented Feb 23, 2015 at 23:19
  • I think the article you site gives bad advice. If the related data is big enough to warrant a relation, then its probably too big to fetch all at once. And the article's idea about how to fetch at once is convoluted. Promise.when() on all of the related queries would do the same job in a couple lines. Commented Feb 24, 2015 at 0:45

1 Answer 1

1

To answer my own question, the answer was actually pretty easy in the end, if you read up about parallel promises in the Parse docs https://parse.com/docs/js_guide#promises-parallel what the example misses is that the function passes to the final then() can accept an array of results, e.g.

Parse.Promise
    .when([query0.find(), query1.find()])
    .then(function (query0Results, query1Results) {
        res.render('index',
            {
                query0Results: query0Results,
                query1Results: query1Results,
            }
        );
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.