質問

I want to use $q to run events but I do (for reasons not relevant to the question) care what order they occur in. How can I use promise.then() to run things sequentially without ending up with heavily nested functions?

Simplified example

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

I know I could name those nested functions and use f1().then(f2).then(f3).then(f4) but is there a better way of doing this?

役に立ちましたか?

解決

Using promises like that is an anti-pattern. Consider this instead which is probably as good as you'll get.

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;
  })
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top