【问题标题】:AngularJS: run asynchronous events sequentially with $q / deferAngularJS:使用 $q / defer 顺序运行异步事件
【发布时间】:2014-03-19 01:41:23
【问题描述】:

我想使用$q 运行事件,但我确实(出于与问题无关的原因)关心它们发生的顺序。我如何使用promise.then() 来按顺序运行事件没有以重度嵌套函数告终?

简化示例

var myGenericFunc = function(arg1,arg2){
  var defer = $q.defer();
  
  doSomeQueryNotActualSyntax(arg1,arg2, someSuccessCallback(){
    defer.resolve('result');
  }
  return defer.promise;
}

// then somewhere else...
var result1,result2,result3,result4;

myGenericFunc('foo','bar').then(function(res){
  result1 = res;
  myGenericFunc('baz','qux').then(function(res){
    result2 = res;
    myGenericFunc('quux','corge').then(function(res){
      result3 = res;
      myGenericFunc('grault','garply').then(function(res){
        result4 = res;
      });
    });
  });
});

我知道我可以命名这些嵌套函数并使用f1().then(f2).then(f3).then(f4),但有更好的方法吗?

【问题讨论】:

  • f1.then(f2).then(f3).then(f4) 就是这样。每个函数都应该返回一个 promise。
  • 谢谢,效果很好。
  • (接受的答案其实是一回事)

标签: angularjs promise q


【解决方案1】:

使用这样的 Promise 是一种反模式。考虑一下,这可能与您将获得的一样好。

myGenericFunc('foo', 'bar')
.then(
  function(res){
    result1 = res;
    return myGenericFunc('baz','qux');
  })
.then(
  function(res){
    result2 = res;
    return myGenericFunc('grault','garply');
  })
.then(
  function(res){
    result3 = res;
    return myGenericFunc('quux','corge');
  })
.then(
  function(res){
    result4 = res;
  })

【讨论】:

  • 是的,这就是我要找的语法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 1970-01-01
  • 2018-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多