AngularJS-等待多个资源查询完成

我用 ngResource 定义了一个工厂:

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

我对这个工厂上定义的查询方法进行了多次调用。这些调用可以异步发生,但在继续之前,我需要等待两个调用都完成:

App.controller('AccountsCtrl', function ($scope, Account) {
$scope.loadAccounts = function () {
var billingAccounts = Account.query({ type: 'billing' });
var shippingAccounts = Account.query({ type: 'shipping' });


// wait for both calls to complete before returning
};
});

有没有一种方法可以用 ngResource 定义 AngularJS 工厂,类似于 jQuery 的 $。什么时候。那么()功能呢?我不希望将 jQuery 添加到我当前的项目中。

74244 次浏览

You'll want to use promises and $q.all().

Basically, you can use it to wrap all of your $resource or $http calls because they return promises.

function doQuery(type) {
var d = $q.defer();
var result = Account.query({ type: type }, function() {
d.resolve(result);
});
return d.promise;
}


$q.all([
doQuery('billing'),
doQuery('shipping')
]).then(function(data) {
var billingAccounts = data[0];
var shippingAccounts = data[1];


//TODO: something...
});

I think a better solution is:

$q.all([
Account.query({ type: 'billing' }).$promise,
Account.query({ type: 'shipping' }).$promise
]).then(function(data) {
var billingAccounts = data[0];
var shippingAccounts = data[1];


//TODO: something...
});

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.