0

I'm having trouble with repeating data from a loop (which is not accurate, the data should be unique). I believe the problem is due to a poor implementation/understanding of promises.

var posts = PostsData.getPosts();      

$scope.$watch($scope.active, function() {
    $timeout(function() {
        var markers = [];

        for (var key in posts) {
            var post = posts[key];
            if (posts.hasOwnProperty(key) && posts[key]!=null) {
                var p = $q.defer();
                p = gf.get(key).then(function(location) { 
                    console.log(post.title)

                    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;
        });

    });
})

}

$scope.markers is filled with repeating post.title data. Any help would be greatly appreciated. I'm new to programming, so I apologize if my issues seem simple.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
P K
  • 3
  • 2
  • That `$q.defer();` doesn't make sense there. You should just initialise with `var p = gf.get(…).then(…)` – Bergi Mar 22 '16 at 00:38
  • Also, if `posts` is an array, have a look at [why using `for…in` on arrays is such a bad idea](https://stackoverflow.com/q/500504/1048572). Use [`markers = posts.map(…)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) instead, which also solves your other problem. – Bergi Mar 22 '16 at 00:40

1 Answers1

0

Try to replace:

var p = $q.defer();
p = gf.get(key).then(function(location) {
   ...
})

with p = gf.get(key);

olysachok
  • 311
  • 2
  • 8