title: AngularJS - Processing asynchronous data in service
body: <p>I want to get some asynchronous data in service, which needs to further processed there. The code is here at <a href="http://plnkr.co/edit/6SkzXK?p=preview" rel="nofollow">plnkr</a>, </p>
  
  <p>I simulate an async call with timeout, and once the data is received, the UI is updated.
  But, I also need to process the data in service (doubleData) and later use in my UI. Say, I need to augment the data with some specifics. </p>
  
  <p>Since, data is null when <code>{{doubleData()}}</code> is called, it never populates it. How can I achieve a way to process data further in my service(which is populated async - say $http)?</p>
  
  <h2>index.html</h2>
  
  <pre><code>&lt;!doctype html&gt;
  &lt;html ng-app="myApp"&gt; 
      &lt;head&gt;
          &lt;script type="text/javascript" src="../../../angular-1.0.2/angular.js"&gt;&lt;/script&gt;
          &lt;script type="text/javascript" src="script.js"&gt;&lt;/script&gt;
      &lt;/head&gt;
      &lt;body&gt;
          &lt;div ng-controller="MainCtrl"&gt;
              {{data}}&lt;br&gt;
              {{doubleData()}}
          &lt;/div&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <h2>script.js</h2>
  
  <pre><code>var app = angular.module('myApp',[]);
  
  app.factory('myService', function($timeout) {
    var data = [],
        doubleData = [];
  
    var myService = {};
    myService.async = function() {
      $timeout(function(){
          data.length = 0;
          for(var i = 0; i &lt; 10; i++){
              data.push({val: Math.random()});                        
          }
      }, 5000); 
    };
    myService.data = function() { return data; };
    myService.doubleData = function() { 
      doubleData = []
      for (var i = 0; i &lt; data.length; i++) {
          doubleData.push({val: 10* data[i]});   
      };    
      return doubleData;                 
    };
  
    return myService;
  });
  
  app.controller('MainCtrl', function( myService,$scope) {
    myService.async();
    $scope.data = myService.data();
    $scope.doubleData = myService.doubleData;
  
  });
  </code></pre>
  
  <h2>Output (after 5 sec):</h2>
  
  <pre><code>[{"val":0.4908415926620364},{"val":0.25592787051573396},{"val":0.8326190037187189},{"val":0.6478461190126836},{"val":0.8502937415614724},{"val":0.19280604855157435},{"val":0.06115643493831158},{"val":0.5100495833903551},{"val":0.4134843284264207},{"val":0.5548313041217625}]
  [{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null},{"val":null}]
  </code></pre>