Call a promise function multiple times until condition met from another promise function

╄→гoц情女王★ 提交于 2019-12-09 03:09:28

When you declare deferred outside and recursively call your function the innermost recursive call will resolve the deferred.promise from the outside. When it's declared inside, only the inner-most promise gets resolved (but it's never returned). Consider this fiddle which kind of illustrates a similar variable scoping issue:

https://jsfiddle.net/sg6odtof/

var counter = 5;

var a = "outside";
function b() {
  //If you uncomment this, the behavior of b is different.
  //var a = "inside";
  if (counter > 0) {
    counter--;
    b();
  }

  return a;
}

alert(b());

I'm guessing you don't like that variable outside the function; therefore I think what you want to do is have the outer recursion return the inner-recursion's promise.

http://jsfiddle.net/pLns9mjw/1/

function callPromise() {  
    return getActiveTasks().then(function(){
        if($scope.count < 5) {
            return callPromise();
        }
    });
}

Also, not sure what you're trying to do for real consider $q.all which takes in an array of promises and resolves when all promises are done. As long as your tasks were known in advance, that's easy if you just want to notify when they're all done.

If the ongoing tasks is dynamic which might get added, you could $q.all them, and check to see if any are left when that promise is done until there are none left.

If you want to just do an ongoing status that reports to the user when you're at certain thresholds a timeout approach like yours is fine.

Note you should use $timeout instead of vanilla JavaScript timeouts so that any changes to the $scope don't happen outside the Angular's digest cycle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!