AndreFontaine AndreFontaine - 3 months ago 20
Javascript Question

Chaining promises in Javascript and Angular

I am using Angular resourse to get my data from an API, in this way:

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 it and another two service functions defined in the same way.

var promiseResourcesAccountList = usrWebUserService.getAccountListPerUser();

promiseResourcesAccountList.then(function(result){
$scope.usersWithAccountsAndProfiles = result;
var filteredProfiles = [];
for (var account in result) {
...
}
$scope.filteredProfiles = filteredProfiles;
});


And:

var promiseResourcesEditUser = usrWebUserService.getResourcesUser(currentUser);

promiseResourcesEditUser.then(function (result) {
usrWebUserFactory.mapBasicPreferences($scope, result);
});


And then another very similar, this information loads data in three divs, but I want to show them only when all the three functions have completed correctly. I think I have to chain the result of the promises. How can I do that?

Answer

You can chain them like:

promiseResourcesAccountList.then(function(result){
  ///whatever processing
  //return a promise
  return promiseResourcesEditUser()
}).then(function(){
  return anotherPromise();
}).then(function(){
   //update scope here
});

alternatively, you could also use $q.all([promise1, promise2, promise3]).then(...);