title: How to structure an Angular service so it can handle asynchronous calls?
body: <p>In my Angular application, I have two controllers which both need access to the same data.</p>
  
  <p>Toward that end, I've created a service which will be responsible for holding and providing access to that data:</p>
  
  <pre><code>angular.module("SomeModule").factory( "SomeService", function( $http ) {
  
      var svc = {};
      var data = {};
  
      // on initialization, load data from the server
      $http.get( "somefile.json" )
          .success( function( data ) {
              svc.data = data;
          } );
  
      svc.getItem = function( id ) {
          // find the specified item within svc.data, and return its value
      };
  
      return svc;
  
  } );
  </code></pre>
  
  <p>...and I've injected that service into each of the two controllers:</p>
  
  <pre><code>angular.module("SomeModule").controller( "SomeController", function( $routeParams, SomeService ) {
  
      var ctrl = this;
  
      ctrl.item = null; // set an initial value
  
      // load the item that was requested in the URL
      ctrl.item = SomeService.getItem( $routeParams.id );
  
  } );
  </code></pre>
  
  <p>This <em>almost</em> works - but it has one big flaw. If <code>SomeController</code> calls <code>SomeService.getItem()</code> before <code>SomeService</code> finishes loading <code>somefile.json</code>, then <code>SomeService</code> won't have any data to return.</p>
  
  <p>In practice, if I load the app a few times, some loads will work (<em>i.e.</em>, <code>SomeService</code> <em>will</em> finish loading <code>somefile.json</code> first, and the controller will present the data as desired), and other loads don't (<em>i.e.</em>, <code>SomeController</code> will try to retrieve data from <code>SomeService</code> before the data has actually been loaded, and everything will crash and burn).</p>
  
  <p>Obviously, I need to find some way to defer the execution of <code>getItem()</code> until <code>SomeService</code> is actually ready to process those calls. But I'm not sure of the best way to do that.</p>
  
  <p>I can think of a some rather hairy solutions, such as building my own call queue in <code>SomeService</code>, and wiring up a bunch of complicated callbacks. But there's gotta be a more elegant solution.</p>
  
  <p>I <em>suspect</em> that <a href="https://docs.angularjs.org/api/ng/service/$q" rel="nofollow">Angular's $q service</a> could be useful here. However, I'm new to promises, and I'm not sure exactly how I should use <code>$q</code> here (or even whether I'm barking up the right tree).</p>
  
  <p>Can you nudge me in the right direction? I'd be super grateful.</p>