angularjs – 等待所有promise解决

前端之家收集整理的这篇文章主要介绍了angularjs – 等待所有promise解决前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我有一个情况,我有多个未知长度的承诺链。我想要一些操作运行时,所有的CHAINS已经处理。这是可能吗?这里是一个例子:
  1. app.controller('MainCtrl',function($scope,$q,$timeout) {
  2. var one = $q.defer();
  3. var two = $q.defer();
  4. var three = $q.defer();
  5.  
  6. var all = $q.all([one.promise,two.promise,three.promise]);
  7. all.then(allSuccess);
  8.  
  9. function success(data) {
  10. console.log(data);
  11. return data + "Chained";
  12. }
  13.  
  14. function allSuccess(){
  15. console.log("ALL PROMISES RESOLVED")
  16. }
  17.  
  18. one.promise.then(success).then(success);
  19. two.promise.then(success);
  20. three.promise.then(success).then(success).then(success);
  21.  
  22. $timeout(function () {
  23. one.resolve("one done");
  24. },Math.random() * 1000);
  25.  
  26. $timeout(function () {
  27. two.resolve("two done");
  28. },Math.random() * 1000);
  29.  
  30. $timeout(function () {
  31. three.resolve("three done");
  32. },Math.random() * 1000);
  33. });

在这个例子中,我为promise 1,2和3设置了一个$ q.all(),它将在随机的时间得到解决。然后我将promise添加到一和三的结尾。我想要所有的链解决后,所有的链解决。这里是我运行这段代码时的输出

  1. one done
  2. one doneChained
  3. two done
  4. three done
  5. ALL PROMISES RESOLVED
  6. three doneChained
  7. three doneChainedChained

有没有办法等待链解决

I want the all to resolve when all the chains have been resolved.

当然,然后只是通过每个链的承诺到all(),而不是初始的承诺:

  1. $q.all([one.promise,three.promise]).then(function() {
  2. console.log("ALL INITIAL PROMISES RESOLVED");
  3. });
  4.  
  5. var onechain = one.promise.then(success).then(success),twochain = two.promise.then(success),threechain = three.promise.then(success).then(success).then(success);
  6.  
  7. $q.all([onechain,twochain,threechain]).then(function() {
  8. console.log("ALL PROMISES RESOLVED");
  9. });

猜你在找的Angularjs相关文章