Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to avoid multiple ajax requests to the server in a factory. I already added a small caching service, but it is not enough for what I aim: this factory can be called several times before the server responds, causing the generation of multiple requests to the server.

To avoid this I added a second promise object, which if the AJAX request have been performed and the object is not yet in cache, than it should wait for a second promise to be resolved, but looks like I am missing something.

This is my code:

myApp.factory('User', ['Restangular', '$q',
  function (Restangular, $q) {
    var userCache, alreadyRun = false;
    return {
      getUser: function () {
        var deferred = $q.defer(), firstRun= $q.defer();

        if (!userCache && !alreadyRun) {
          alreadyRun = true;

          Restangular.all('user').getList().then(function (user) {
            console.log('getting user live ');
            userCache = user[0].email;
            firstRun.resolve(user[0].email);
          });
        } else if (!userCache && alreadyRun) {
          console.log('waiting for the first promise to be resolved ');
          firstRun.then(function(user) {
            console.log('resolving the promise');
            deferred.resolve(userCache);
          });

        } else {
          console.log('resolving the promise from the cache');
          deferred.resolve(userCache)
        }
        return deferred.promise;
      }
    };
  }
]);
share|improve this question
add comment

1 Answer

Everytime you run getUser, a new defer is created for firstRun. If it's already ran, you call firstRun.then, but that promise is never resolved.

share|improve this answer
 
But there is any way to achieve what am I trying to do? –  mimo yesterday
 
Can't tell you without more context. GetUser is being called from a bunch of places at once? You can use Resolve on a route to make sure it's loaded before you start doing things. –  Jonathan Rowny yesterday
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.