简体   繁体   中英

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?

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

@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);           
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM