我试图从Parse.com获取所有帖子,并检查当前用户是否喜欢每个帖子。据我所知,内部查询不能在for循环中完成,因为它是异步函数。我不明白如何以允许我检查每个帖子的方式格式化它。我尝试了$ q.defer(),但它也没有用。任何帮助将不胜感激
var imageGallery = Parse.Object.extend("Gallery");
var query = new Parse.Query(imageGallery);
query.include("user");
query.near("location", $rootScope.currentLocation);
query.find({
success: function(results) {
var i = 0;
for (i; i < results.length; i++) {
var object = results[i];
var galleryLike = Parse.Object.extend("GalleryLike");
var likeQuery = new Parse.Query(galleryLike);
likeQuery.include('gallery');
likeQuery.include('user');
likeQuery.equalTo('gallery', object);
likeQuery.equalTo('user', Parse.User.current());
likeQuery.find({
success: function(res) {
if (res.length == 0) {
var like = "false";
} else {
var like = "true";
}
},
error: function(error) {
}
});
var distance = object.get('location').kilometersTo($rootScope.currentLocation);
self.images.push({
object: object,
locationName: object.get('locationName'),
caption: object.get('caption'),
img: object.get('img').url(),
username: object.get('user').get('username'),
userprofpic: object.get('user').get('profpic').url(),
distance: distance,
isLiked: like
});
}
$scope.$apply();
$ionicLoading.hide();
},
error: function(error) {
$ionicLoading.hide();
}
});
答案 0 :(得分:1)
定义一个只获得一个帖子的函数,比如getPost()
,它会返回一个promise。
然后您可以使用$q.all()
,如下所示:
var promises = [];
for (var i < results.length; i++) {
promises.push(getPost(i));
}
$q.all(promises)
.then(function(results){
// results[i] is relevant to post #i
});