Angular promise resolves internal function, but not outside

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"); }); }); 
+5
source share
1 answer

Check this script .

The outter $timeout function is called so that it can be called internally.

 $timeout(function inner() { // ... 

Then it is called recursively as follows:

 $timeout(function () { inner(); }, 400); 
+1
source

Source: https://habr.com/ru/post/1201186/


All Articles