title: AngularJS: Why is .then() not waiting for the promise object to arrive
body: <p>I have created the following angular service for the purpose of making the API calls.</p>
  
  <pre><code>(function (module) {
      module.service('APIService',function ($http, $q) {
          console.log("Reached APIService")
          var deferred = $q.defer();
          this.getData = function (requestURL) {
              console.log("Reached APIService @GET", requestURL);
              $http.get(requestURL).success(
                  function (data, status) {
                      deferred.resolve(data);
                      console.log("In service",status,data);
                  }).error(
                  function (data, status) {
                      deferred.reject(data);
                      console.log(status);
                  });
              return deferred.promise;
          };
  
          this.postData = function (requestURL, requestObj) {
              console.log("Reached APIService @POST", requestURL, requestObj);
              $http.post(requestURL, requestObj).success(
                  function (data, status) {
                      deferred.resolve(data);
                      console.log(status);
                  }).error(
                  function (data, status) {
                      deferred.reject(data);
                      console.log(status);
                  });
              return deferred.promise;
          };
      });
  }(angular.module("MainApp")));
  </code></pre>
  
  <p>I have injected it in my two controllers. However, I am facing following issues:</p>
  
  <ol>
  <li><p>When I call it first time in first controller, it works fine and returns the desired result. However, when I call it in second controller as follows:</p>
  
  <pre><code>    APIService.getData(Config + headerURL).then(function (response) {
          console.log(Config + headerURL);
          console.log("header response from API", response);
  
      },function(error) {
          console.log("API call for header data failed");
      });
  </code></pre></li>
  </ol>
  
  <p>Since my service returns a promise object, I don't expect the code inside .then() to work before the service data arrives.
   However, it runs before service data arrives (no clue how). The most strange thing is that the response that I get inside .then() is not actually the response from this URL (Config+headerURL), but it is the response that was obtained from a different URL previously called in first Controller using the same APIService service.</p>
  
  <p>Just to inform: the actual response from current URL do arrive at a later stage.</p>
  
  <p>I am aware of asynchronous callings and I think it has something to do in this case, but I guess .then() handles it in Angular. So I am confused what is the issue here. Can anyone shed some light please?</p>