繁体   English   中英

AngularJS:这是链接承诺的正确方法吗?

[英]AngularJS : Is this the correct way to chain promises?

我有一个函数foo ,它调用另一个函数moreFoo,并且我想将该函数调用包装在promise中,以便foo返回的promise在moreFoo解决后返回。 这是我的解决方案:

function foo() {
  var defer = $q.defer();
  console.log('doing foo');
  moreFoo().then(defer.resolve);
  return defer.promise;
}

function moreFoo() {
  var defer = $q.defer();
  setTimeout(function() {
    console.log('doing more foo');
    defer.resolve();
  }, 2000);
  return defer.promise;
}

foo().then(function() {
  console.log('finished with all foos');
});

然后输出:

 doing foo doing more foo finished with all foos 

它似乎按预期工作。 这是兑现这些承诺的正确/最佳方法吗?

我对“最佳”一无所知,但是可以通过利用$timeout它将返回的承诺来简化很多工作……

function foo() {
  console.log('doing foo');
  return moreFoo();
}

function moreFoo() {
  return $timeout(function() {
    console.log('doing more foo');
  }, 2000);
}

foo().then(function() {
  console.log('finished with all foos');
});

我喜欢这种方式($ timeout返回promise):

 function foo() {
      return $timeout(function(){
           console.log('doing foo');
       },2000);
 }

 function moreFoo() {
      return $timeout(function(){
           console.log('doing more foo');
       },2000);
 }        

 foo()
     .then(moreFoo)
     .then(function(){ 
          console.log('all foos done');
      }, function() {
         console.log('something went wrong');
      });

这个例子显示了两个诺言链接在一起。 第二个仅在第一个成功后才执行。 如果任何一个失败,则调用最后一个错误处理程序。

可以同时运行,甚至不需要使用$q.all()链接它们

$q.all([ foo(), moreFoo()]).then(function(data){
    console.log(data) /* array of responses from all resolved promises */
});

良好的参考: https : //egghead.io/lessons/angularjs-q-all

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM