$q.all and nested promises

前端 未结 1 1700
后悔当初
后悔当初 2021-01-18 13:04

Have a question about synchronizing nested promises when using $q in Angular. Will the following code ensure that the entire chain of promises is waited for? Meaning will th

1条回答
  •  盖世英雄少女心
    2021-01-18 13:25

    Yes it looks like Kevin is correct. I created a quick test in angular as well to confirm the behavior.

    angular.module('myModule').controller('testController', function ($q,$scope) {
    
      function promiseCall(data,timeout) {
        var deferred = $q.defer();
    
        setTimeout(function() {
          deferred.resolve(data);
          console.log(data);
        }, timeout);
    
        return deferred.promise;
      }
    
      var a = promiseCall('call1 a',1000).then(function(){
        return promiseCall('call2 a',50);
      });
    
      var b = promiseCall('call1 b',500);
    
      var c = promiseCall('call1 c',1000).then(function(){
        return promiseCall('call2 c',50).then(function(){
          return promiseCall('call3 c',6000);
        });
      });
    
      $q.all([a,b,c]).then(function(res){
        console.log('all calls are done');
      });
    
    });
    

    0 讨论(0)
提交回复
热议问题