0

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?

1
  • 2
    Using Promise.all([array of your promises]). Here the documentation. Commented Aug 12, 2016 at 15:46

2 Answers 2

1

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(...);

Sign up to request clarification or add additional context in comments.

Comments

0

@terpinmd is correct. Chaining promises is pretty simple. Say you have a service with a "getWidgets" that returns a promise, and you want to use the response from that service to call another service, "getWidgetOwners" that will return another promise :

Assumptions

  1. getWidgets returns an array of widget objects.
  2. getWidgetOwners accepts an array of ownerIds

How To:

    service.getWidgets()
        .then(function(widgets) {
            return widgets.map(function(widget) { // extract ownerIds 
                return widget.ownerId;
            });
        })
        .then(service.getWidgetOwners)            // pass array of ownerId's to       
        .then(function(owners) {                  // the next service
            console.log(owners);           
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.