Angularjs:$ q.defer和异步调用

时间:2022-06-12 20:34:30

I am calling a $resource in a loop.
I want to call another $resource once all the calls in the loop are done.

我在一个循环中调用$资源。一旦循环中的所有调用完成,我想调用另一个$资源。

I have searched and found about $q.defer, but I don't know how to apply it to my example :

我搜索并发现了$ q.defer,但我不知道如何将其应用于我的示例:

for (var i=0; i<$scope.fraiss.length; i++){
   var frais = {};
   //copy some properties values of $scope.fraiss[i] in frais then persist frais
   FraisVente.save(frais)
}
MyNextService.query();

If anyone can help me on this...

如果有人可以帮我这个...

Thanks

1 个解决方案

#1


1  

You want to use $q.all()

你想使用$ q.all()

From the angular docs:

从角度文档:

all(promises);
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

所有的(承诺);将多个promise组合成单个promise,在解析所有输入promise时解析。

var promises = [];

for (var i=0; i<$scope.fraiss.length; i++){
 var frais = {};
 //copy some properties values of $scope.fraiss[i] in frais then persist frais
 promises.push(FraisVente.save(frais));
}

$q.all(promises).then(function() {
  MyNextService.query();
}

#1


1  

You want to use $q.all()

你想使用$ q.all()

From the angular docs:

从角度文档:

all(promises);
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

所有的(承诺);将多个promise组合成单个promise,在解析所有输入promise时解析。

var promises = [];

for (var i=0; i<$scope.fraiss.length; i++){
 var frais = {};
 //copy some properties values of $scope.fraiss[i] in frais then persist frais
 promises.push(FraisVente.save(frais));
}

$q.all(promises).then(function() {
  MyNextService.query();
}