I'm an Angular noob, and I'm still getting used to the way Promises work.
I have a use case where I need to populate a collection with the results of an $http call to a JSON WS. Each call to this WS returns a variable number of objects (always more than 20), however I want my arrays to collections have 20 elements.
When the collection is filled with 20 elements, I need to perform some actions. Due to the asynchronous nature of promises (e.g. I can't simply add the logic below the promises, as it will be executed before them) I've been struggling for some time to do this and came up with two approaches, though I wonder if there's any other way to achieve what I want - they don't seem like a good solution. $scope.renderedTracks holds the collection.
Attempt 1 - $watchCollection
    $scope.updateTracks = function() {
        if ($scope.renderedTracks.length == 20)
        {
           // Do the desired actions
        }
      };
    $scope.$watchCollection('renderedTracks', $scope.updateTracks);
Attempt 2 - Performing the check inside the promise
$http.get('https://localhost/artists' + artistId + '/related-artists').then(function (response) {
            for (i = 0; i < 20; i++)
            {
                //Get random artist from user's favorite artists
                artistIndex = Math.floor(Math.random() * response.data.artists.length);
                artistId = response.data.artists[artistIndex].id;
                $http.get('https://localhost/artists' + artistId + '/top-tracks').then(function (response) {
                    track = response.data.tracks[Math.floor(Math.random() * response.data.tracks.length)];
                    if (track)
                    {
                        track.originalArtist = artistName;
                        $scope.renderedTracks.push(track);
                        if ($scope.renderedTracks.length == 20)
                        {
                           // Do required actions
                        }
                    }
                }, function (err) {
                    console.log(err);
                });
        }
      }, function (err){
            console.log(err);
       });
Thanks in advance.
