AngularJS等到很多$ timeout完成

时间:2014-11-28 15:08:23

标签: angularjs

如何等待所有AngularJS' $timeouts已完成?

for (var i = 0; i < 1000; i++) {
   $timeout(function () {
      //do sth
   }, 100);
};

//then do something else is all $timeouts are done

1 个答案:

答案 0 :(得分:3)

您可以使用超时返回的承诺,并使用$q.all(注入$q)的组合来实现这一目标。

实施例: -

var promises = [];

for (var i = 0; i < 1000; i++) {
  promises.push(performTask(i)); //push promise to the array
}


//If in your real case i is actually an array of something then you can 
//just simplify it to $q.all(myArrayOfInputs.map(performTask)).then(...)

$q.all(promises).then(performDoneTask); //use q.all to wait for all promises to be fulfilled.

//Method that does something once all the timeouts are completed
function performDoneTask(){

}

//Method that does something with i and returns a promise from the timeout
function performTask(i){ 
  return $timeout(function () {
      //do sth
   }, 100);
}