API calls with a getToken promise

I am using a factory to get the token, or refresh it if necessary and then return the token, so it's an async call. I need that the interceptor waits until the getToken() is resolved, but I can not figure how to resolve it out.

EDIT: I solved it using $q.defer() like:

// Config
app.config(function ($httpProvider) {

  $httpProvider.interceptors.push(['$q', '$injector', function ($q, $injector) {
    return {
      // On request success
      request: function (config) {
      var deferred = $q.defer();

        if ( API_CALL ) {
            // If any API resource call, get the token firstly
            $injector.get('AuthenticationFactory').getToken().then(function (token) {
              config.headers.Authorization = 'Bearer '+token;

              deferred.resolve(config);
            });
          } else {
            deferred.resolve(config);
          }
        } else {
          deferred.resolve(config);
        }

        return deferred.promise;
      },

      response: function (response) {
        // Return the promise response.
        return response || $q.when(response);
      }
    };
  }]);

});

Is there any alternative implementation?

1 Like

Do it work for you? Because when promise is returned from request function app fails.