0

This is a follow up question for Angularjs $http wait for response

Since i was unable to find a solution for that, i thought i will return a promise always and let my directive do the work in promise.then() function.

$scope.getVCard = function(id){

  var vcardKey = vcardKeyPrefix+id;

  var vCardFromLS = localStorageService.get(vCardKey);
  if(vCardFromLS){
    var deferred = $q.defer();
    deferred.resolve({data:localStorageService.get(vCardKey)});
    return deferred.promise;
  }
}

and in my directive i am using it as

(function(angular, app) {
  app.directive('popOver',["$window","$http",function($window,$http){
    return function(scope,elem,attrs){
      elem.on('mouseover',function(){
        console.log('mouseover');
        var promise = scope.$apply(attrs.popOver);
        promise.then(function(data){
          console.log('promise then called');
          console.log(data);
          //logic here
        });
        console.log('in directive again');
        console.log(data);
      });
    };
  }]);
})(angular, app);

But promise.then() is not getting invoked on first time. It gets invoked and works fine on subsequent mouse overs. What can be the issue?

I tried adding $scope.$apply() just before return deferred.promise but i am getting apply already in progress error. What am i missing here?

3
  • You're only returning a promise if vCardFromLS is found. Are you sure it always exists? Commented Jun 28, 2013 at 17:42
  • yeah... it is always there. Actually there will be an if else in which if the item is not found i will trigger a $http request. Commented Jun 28, 2013 at 17:45
  • I think your use of scope.$apply confused Angular. Here is a slighty rewritten version that seems to work okay. Commented Jun 28, 2013 at 17:59

1 Answer 1

1

I believe it is because you are resolving it before returning it. I could be wrong though.

Try this:

$scope.getVCard = function(id){
  var vcardKey = vcardKeyPrefix+id,
    vCardFromLS = localStorageService.get(vCardKey),
    deferred = $q.defer();
  if(vCardFromLS){
    $timeout(function(){
      deferred.resolve({data:vCardFromLS});
    }, 100);
  } else {
    $timeout(function(){
      deferred.reject();
    }, 100);
  }
  return deferred.promise;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Resolving a deferred before returning/using its promise isn't a problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.