title: AngularJS Promise being rejected without waiting for async response (it should resolve)
body: <p>In my scenario, when a visitor navigates to a page (or route) of the first time they should be anonymously authenticated (I'm using Firebase). For context; later on the visitor may migrate their anonymous session after they have logged in, with Facebook, for example.</p>
  
  <p>If the anonymous authentication fails for some reason, they are redirected to an error page (route) -- one of few pages that do not require any authentication.</p>
  
  <p>I am using promises to:</p>
  
  <ol>
  <li>check if the visitor is already authenticated</li>
  <li>if they are not, try and anonymously authenticate them</li>
  <li>if they are authenticated successfully, resolve the promise (and route)</li>
  <li>if the authentication fails for some reason, reject the promise</li>
  </ol>
  
  <p>Question:</p>
  
  <p>The promise always seems to be rejected the first time a visitor navigates to a page (route) that requires authentication, even when the visitor has been anonymously authenticated successfully (in step 2 above); why would this be happening?</p>
  
  <p>Below I have included my code, and added a comment to highlight the section that seems to be causing the problem.</p>
  
  <p>Thanks for your help with this, it is always appreciated!</p>
  
  <pre><code>var app = angular.module('vo2App', ['firebase', 'ngCookies', 'ngRoute']);
  
  app.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
  
    $routeProvider
    .when('/', {
      controller: 'HomeCtrl',
      templateUrl: '/views/home.html'
    })
    .when('/login', {
      controller: 'LoginCtrl',
      templateUrl: '/views/login.html'
    })
    .when('/oops', {
      controller: 'OopsCtrl',
      resolve: {
        currentAuth: function (){
          return null;
        }
      },
      templateUrl: '/views/oops.html'
    });
  }]);
  
  app.run(['$location', '$rootScope', 'Auth', 'ErrorMsg', function ($location, $rootScope, Auth, ErrorMsg) {
    $rootScope.$on('$routeChangeError', function (event, next, prev, error) {
      if (error === 'AUTH_REQUIRED') {
        ErrorMsg.add('Unauthorized');
        // TODO: Make all error messages constants
  
        $location.url('/oops');
      }
    });
  
    $rootScope.$on('$routeChangeStart', function (event, next, current) {
      if (! ('resolve' in next)) {
        next.resolve = {};
      }
  
      if (! ('currentAuth' in next.resolve)) {
        next.resolve.currentAuth = function ($q, Auth) {
          var deferred = $q.defer();
  
          Auth.$requireAuth().then(deferred.resolve, function () {
  
            /* ** The following line seems to be causing the problem ** */
  
            Auth.$authAnonymously().then(deferred.resolve, deferred.reject('AUTH_REQUIRED'));
          });
  
          return deferred.promise;
        };
      }
    });
  }]);
  </code></pre>