Please take a look at my code.
var posts = PostsData.getPosts();
var postFunc = function(key) {
return posts[key];
}
$scope.$watch($scope.active, function() {
$timeout(function() {
var markers = [];
for (var key in posts) {
console.log(key);
var p = gf.get(key).then(function(location) {
var post = postFunc(key);
console.log(key);
return ({
idKey: key,
title: post.title,
coords: {
latitude: location[0],
longitude: location[1]
}
});
});
markers.push(p);
}
$q.all(markers).then(function(markers) {
$scope.markers = markers;
});
});
})
}
Within the loop there are two lines of "console.log(key)". The first console.log prints an accurate representation of the data which is unique keys. The second console.log prints repeating identical data, which is inaccurate. I'm having trouble understanding why this is happening.
Thanks so much for the help.
it is quite normal that from second console.log(key)
onward you have same value. The reason for that is your async function gf.get(key).then(function(location) { .. }
. By the time this function is called your loop has finished execution and the value of key
is the last value from your loop. I am not sure what gf.get
do but if posts
is an array you can achieve your result with help of recursion as shown below
var posts = PostsData.getPosts();
var postFunc = function(key) {
return posts[key];
}
var markers = [];
var getMarkers(key) {
if (key > posts.length - 1) {
// promise resolved for each item in posts
$q.all(markers).then(function(markers) {
$scope.markers = markers;
}
return;
}
console.log(key);
gf.get(key).then(function(location) {
var post = postFunc(key);
console.log(key);
markers.push({
idKey: key,
title: post.title,
coords: {
latitude: location[0],
longitude: location[1]
}
});
getMarkers(++key);
});
}
$scope.$watch($scope.active, function() {
markers = [];
getMarkers(0);
});
Note: In this approach we wait for each promise to be resolved before moving to next call of gf.get