AngularJS - wait for multiple resource queries to complete

前端 未结 3 1563
遥遥无期
遥遥无期 2020-11-29 17:57

I have a single factory defined with ngResource:

App.factory(\'Account\', function($resource) {
    return $resource(\'url\', {}, {
        query: { method:          


        
3条回答
  •  天涯浪人
    2020-11-29 18:15

    The solution from Ben Lesh is the best but it's not complete. If you need to handle error conditions--and, yes, you do--then you must use the catch method on the promise API like this:

    $q.all([
       doQuery('billing'),
       doQuery('shipping')
    ]).then(function(data) {
       var billingAccounts = data[0];
       var shippingAccounts = data[1];
    
       //TODO: something...
    
    }).catch(function(data) {
    
       //TODO: handle the error conditions...
    
    }).finally(function () {
    
      //TODO: do final clean up work, etc...
    
    });
    

    If you don't define catch and all of your promises fail, then the then method won't ever execute and thus will probably leave your interface in a bad state.

提交回复
热议问题