1

我有一个函数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

它似乎按预期工作。这是链接这些承诺的正确/最佳方式吗?

4

3 回答 3

2

我不知道“最佳”,但这可以通过利用$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');
});
于 2014-07-16T00:13:20.810 回答
0

可以同时运行,甚至不需要通过使用链接它们$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

于 2014-07-16T00:43:24.597 回答
0

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

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

这个例子展示了两个链接在一起的 Promise。第二个仅在第一个成功后执行。如果其中一个失败,则调用最后一个错误处理程序。

于 2014-07-16T00:22:40.610 回答