Call a promise function multiple times until condition met from another promise function
I have the following code: http://jsfiddle.net/kyy4ey10/4/ $scope.count = 0; function getActiveTasks() { var deferred = $q.defer(); setTimeout(function() { $scope.count++; deferred.resolve(); },1000) return deferred.promise; } // i want to put this inside the function, but it doesn't work var deferred = $q.defer(); function callPromise() { getActiveTasks().then(function(){ if($scope.count < 5){ callPromise(); } else{ deferred.resolve() } }) return deferred.promise; } callPromise().then(function(){ $scope.count = "done" }); If I put: var deferred = $q.defer(); inside the callPromise() function,