title: AngularJS: run asynchronous events sequentially with $q / defer
body: <p>I want to use <code>$q</code> to run events but I <strong>do</strong> (for reasons not relevant to the question) care what order they occur in. How can I use <code>promise.then()</code> to run things sequentially without ending up with heavily nested functions?</p>
  <h3>Simplified example</h3>
  <pre><code>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;
        });
      });
    });
  });
  </code></pre>
  <p>I know I could name those nested functions and use <code>f1().then(f2).then(f3).then(f4)</code> but is there a better way of doing this?</p>