Reputation: 3
I am quite new to Parse and I am struggling with a particular query. I have a class User
a class Post
and a class Comment (I guess my configuration is pretty standard) I do not have enough reputation to post pictures - how sad that sounds - :-)
I have a query where basically I select all the posts (and the related users and ideally I would like to have all the comments related to the post) To do so I do:
var query = new Parse.Query("Post");
query.include("user");
query.find({
success: function(objects) {
for (var i = 0; i < objects.length; i++)
{
var object = objects[i];
console.log(object.id + object.get("user").get("imageUrl") + object.get('text'));
var commentquery = new Parse.Query("Comment");
commentquery.equalTo("post", object);
commentquery.find({
success: function(comments) {
console.log(object.id + object.get("user").get("imageUrl") + object.get('text'));
where basically I try to get the posts and then fetch the comments for each of them. Unfortunately, the second console log in my code always prints the same object (like ignoring the for loop).
I really don't know what am I doing wrong (maybe the callbacks or maybe the query setup) but I am not able to overcome this. Also, if any expert knows a better way of doing this without getting redundant with data or knows a good tutorial / book on Parse (apart from the Parse Documentation) I will be really grateful.
Thanks in advance!
Upvotes: 0
Views: 244
Reputation: 2832
Use an anonymous function to close your work on object.
for (var i = 0; i < objects.length; i++)
{
var object = objects[i];
(function(object){
//do stuff with object;
})(object);
}
You're using the most recent object because the work after the assignment has not yet finished so objects[i] is going to the next one too early. The extra function should help.
Or you can just
for (var i = 0; i < objects.length; i++)
{
(function(object){
//do stuff with object;
})(objects[i]);
}
Closures and the infamous loop problem
Upvotes: 0