$ q.all和嵌套的承诺

时间:2014-10-03 18:07:58

标签: angularjs q angular-promise

在Angular中使用$ q时,有一个关于同步嵌套promises的问题。 以下代码是否会确保等待整个承诺链?在$ q.all块中等待返回promise的服务的嵌套调用是什么意思?

var call1 = service1.get('/someUr').then(function(){
  return service2.get('/someUrl2'); //returns promise
});

var call2 = service3.get('/someUr').then(function(){
  return 'hello';
});

var call3 = service4.get('/someUr').then(function(){
  return service3.get('/someUrl3');//returns promise
});

$q.all(call1,call2,call3).then(function(){
  console.log('All asynch operations are now completed');
});

基本上:当前代码是否有可能在解决所有嵌套的promises之前执行$ q.all的then?还是递归?

1 个答案:

答案 0 :(得分:4)

是的,看起来凯文是正确的。我还创建了一个角度快速测试来确认行为。

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

});