AndreFontaine AndreFontaine - 2 months ago 5x
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

In my controller I have to use it and another two service functions defined in the same way.

var promiseResourcesAccountList = usrWebUserService.getAccountListPerUser();

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


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?


You can chain them like:

  ///whatever processing
  //return a promise
  return promiseResourcesEditUser()
  return anotherPromise();
   //update scope here

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