I have a recursive function that checks some data every half second or so. The function returns a promise. As soon as I find the data, I want to resolve the promise and pass the data as permission. The problem is that the promise will not call .then () outside the function. Here's the fiddle: http://jsfiddle.net/btyg1u0g/1/ .
Here is the script code:
Services:
myApp.factory('myService', function($q, $timeout) { var checkStartTime = false; var checkTimeout = 30000; function checkForContent() { var deferred = $q.defer(); // simulating an $http request here $timeout(function () { console.log("Checking..."); if (!checkStartTime) checkStartTime = new Date(); // this would normally be 'if (data)' if ((new Date()) - checkStartTime > 3000) { deferred.resolve("Finished check"); checkStartTime = false; // reset the timeout start time } else { // if we didn't find data, wait a bit and check again $timeout(function () { checkForContent(); }, 400); } }, 5); // then is called in here when we find data deferred.promise.then(function(message) { console.log("Resolved inside checkForContent"); }); return deferred.promise; } return { runCheck: function() { return checkForContent() } } });
Controller:
myApp.controller('MyCtrl', function ($scope, myService) { $scope.name = 'Superhero'; // then is never called myService.runCheck() .then(function (message) { console.log("Resolved outside checkForContent"); }); });
source share