I have to gather data from internet in order to show it and I am using promises in order to make it. I need all the requests to be done in order to proceed with the code. Before executing the finally I need all requests to be done. Here is the code:
var start = function(){
$rootScope.albums = [];
var albums = [];
facebookConnectPlugin.api('/me?fields=albums{cover_photo,name}&access_token=' + $scope.user.authResponse.accessToken, [],
function (response) {
$ionicLoading.show();
var alb = response.albums.data; // array
var sequence = $q.all([]);
angular.forEach(alb, function(album) {
sequence = sequence.then(function() {
return $timeout(function () {
facebookConnectPlugin.api('/' + album.cover_photo.id + '?fields=picture&access_token=' + $scope.user.authResponse.accessToken, null,
function (response) {
album.c = response.picture;
albums.push(album);
},
function (errObj) {
alert(JSON.stringify(errObj));
});
},100);
});
});
sequence.finally(function () {
$rootScope.albums = albums;
$ionicLoading.hide();
$state.go('tab.albums');
});
},function (response) {
alert(JSON.stringify(response));
});
}
I believe I shouldn't use $timeout, but that was the only way I found to make it work. Also, sometimes it doesn't return all the requests. I am definitely doing something wrong. If I use a higher $timeout value, like 5000, I can get all the values, but I dont want to depend on it to make it work. All albums cover needs to be gathered before executing the finally code. What should I change in order to run all the requests before runing the finally function?
I've used this code for reference and also have searched the web for a long time other references: https://gist.github.com/slavafomin/8ee69f447765bc5c5e19