I am using $resource
Angular's service to get data from an API, as follows:
var getAccountListPerUser = function () {
return $resource(uri, {}, {
get: {
headers: service.getDefaultHeaderRequest(),
method: 'GET',
transformResponse: function (data) {
var accountList = [];
try {
accountList = JSON.parse(data);
} catch (e) {
accountList = [];
}
return accountList;
},
isArray: true,
cache: true
}
}).get().$promise;
};
In my controller I have to use this function and two others defined in the same way to fetch more information.
var promiseResourcesAccountList = usrWebUserService.getAccountListPerUser();
promiseResourcesAccountList.then(function(result){
$scope.usersWithAccountsAndProfiles = result;
var filteredProfiles = [];
for (var account in result) {
...
}
$scope.filteredProfiles = filteredProfiles;
});
Y:
var promiseResourcesEditUser = usrWebUserService.getResourcesUser(currentUser);
promiseResourcesEditUser.then(function (result) {
usrWebUserFactory.mapBasicPreferences($scope, result);
});
And then another very similar one, this information loads data in three <divs>
, but I want to display it only when all three functions have completed successfully.
I think I should chain the results of the promises. How can I do this?
Chaining is not what you want. Chaining refers to the following
Which means that each promise that follows it will be executed when the previous one has finished . In addition to that, if any of the following promises fails, the chain is interrupted, but the code of each of the
then
previous ones has already been executed.In your question you put
Which defines that chaining is not the right solution for you.
Combining is the right solution in your case. Combination refers to
The variable
libreria
refers to precisely that, the promise implementation you are using. In case of angular it refers to$q
.Unfortunately the library
$q
doesn't have a method otherwisespread
you could do something like thisYou can also use an item to combine
Your code can be written like this