Waiting for Promises to Resolve in Angular 1.x

Been spending a lot of time in Angular recently. I really enjoy using services with promises to get data back from an API. Sometimes you’ll have cause to want to wait for 2 or more promises to resolve before you act on the data that comes back. Angular provides the $q.all to help you achieve this.

Example Service #1:


angular.module('ActivityApp').service('PersonService', [
  '$resource',
  function ($resource) {
    'use strict';

    var Person = $resource('', null, {
      get: {
        method: 'GET',
        url: '/apis/person'
      }
    }));

    return Person;
  }
]);

Example Service #2:


angular.module('ActivityApp').service('ActivityService', [
  '$resource',
  function ($resource) {
    'use strict';

    var Activity = $resource('', null, {
      query: {
        method: 'GET',
        url: '/apis/activity'
      }
    }));

    return Activity;
  }
]);

Example Controller:


angular.module('ActivityApp').controller('PersonController', [
  '$scope',
  'PersonService',
  'ActivityService',
  function ($scope, PersonService, ActivityService) {
    'use strict';

    $scope.person = PersonService.get();
    $scope.activity = ActivityService.query();

    $scope.resolveAll = function (response) {
      // response is an array of both resolved promises
    };

    $q.all([$scope.person.$promise, $scope.activity.$promise]).then($scope.resolveAll);
  }]);

Now in the $scope.resolveAll function you can act on the data and be sure that you have access to sets of data.

posted in: Front End Development
tagged: , , ,

Comments are closed