AngularJS等待许多$超时完成

时间:2021-09-26 19:45:25

how to wait untill all AngularJS' $timeouts are done ?

如何等待所有AngularJS的超时工作都完成了?

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

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

1 个解决方案

#1


3  

You could use the promises returned by the timeouts and with the combination of $q.all (inject $q) you could achieve that.

您可以使用超时和$q组合返回的承诺。所有(注入$q)您都可以实现这一点。

Example:-

例子:-

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);
}

#1


3  

You could use the promises returned by the timeouts and with the combination of $q.all (inject $q) you could achieve that.

您可以使用超时和$q组合返回的承诺。所有(注入$q)您都可以实现这一点。

Example:-

例子:-

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);
}